Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: Using strings as an object argument?
    primarykey
    data
    text
    <p>Essentially my problem is as follows...</p> <p>In Python, I have a function that will return an output string in the following form:</p> <pre><code>'union(symbol(a), symbol(b))' </code></pre> <p>The function forms found within this string actually exist in an object class called RegExTree. Further this class contains a function to construct a tree data structure using the function "construct()" as shown below:</p> <pre><code>tree = RegExTree() tree.construct(union(symbol(a), symbol(b)) </code></pre> <p>The above two lines of code would work normally, constructing a tree based on parsing the arguments within the construct function. I want to pass in a string in a similar fashion, perhaps this line of code illustrates what I want:</p> <pre><code>tree = RegExTree() expression = 'union(' + 'symbol(' + 'a' + ')' + ', ' + 'symbol(' + 'b' + ')' + ')' tree.construct(expression) </code></pre> <p>Right now the way I have the code written as above it yields an error (in the Linux terminal) as follows: </p> <pre><code>$ Attribute Error: 'str' object has no attribute 'value' </code></pre> <p>Can you coerce Python to interpret the string as a valid argument/line of code. In essence, not as string, but as object constructors.</p> <p>Is there a way to get Python to interpret a string as rather something that would have been parsed/compiled into objects and have it construct the objects from the string as if it were a line of code meant to describe the same end goal? Is what I'm asking for some kind of back-door type conversion? Or is what I'm asking not possible in programming languages, specifically Python?</p> <p>EDIT: Using Michael's solution posited below that involves "eval()", there is one way to hack this into form:</p> <pre><code>tree = RegExTree() a = 'a' b = 'b' expression = 'union(' + 'symbol(' + a + ')' + ', ' + 'symbol(' + b + ')' + ')' tree.construct(eval(expression)) </code></pre> <p>Is there a better way of doing this? Or is it just that the nature of my output as string representing functions is just not a good idea? [Thanks martineau for the correction for my solution edit!]</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload