9codeMan9
9codeMan9

Reputation: 852

Python: Using strings as an object argument?

Essentially my problem is as follows...

In Python, I have a function that will return an output string in the following form:

'union(symbol(a), symbol(b))'

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:

tree = RegExTree()    
tree.construct(union(symbol(a), symbol(b))

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:

tree = RegExTree()      
expression = 'union(' + 'symbol(' + 'a' + ')' + ', ' +  'symbol(' + 'b' + ')' + ')'
tree.construct(expression)

Right now the way I have the code written as above it yields an error (in the Linux terminal) as follows:

$ Attribute Error: 'str' object has no attribute 'value'

Can you coerce Python to interpret the string as a valid argument/line of code. In essence, not as string, but as object constructors.

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?

EDIT: Using Michael's solution posited below that involves "eval()", there is one way to hack this into form:

tree = RegExTree()
a = 'a'
b = 'b'    
expression = 'union(' + 'symbol(' + a + ')' + ', ' +  'symbol(' + b + ')' + ')'
tree.construct(eval(expression))

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!]

Upvotes: 2

Views: 1327

Answers (1)

user849425
user849425

Reputation:

You can use the python built-in eval statement.

A word of caution though... you do not want to run eval() on a string that's coming into your program as external input provided by the user. That could create a security hole where users of your program could run arbitrary Python code of their own design.

In your example it'd look something like this:

tree = RegExTree()      
expression = 'union(' + 'symbol(' + 'a' + ')' + ', ' +  'symbol(' + 'b' + ')' + ')'
tree.construct( eval(expression) ) # Notice the eval statement here

Upvotes: 3

Related Questions