[pythonvis] Re: question about converting strings to variables?

  • From: "Richard Dinger" <rrdinger@xxxxxxxxxx>
  • To: <pythonvis@xxxxxxxxxxxxx>
  • Date: Sun, 21 Jun 2015 08:35:21 -0700

As Les said use this with care as it can be dangerous. But Python recognizes we are all adults so ...

Here is a solution using the built in function execfile. First you need a file containing the definitions you want to add in. Here is your sample with the second item corrected (lambda was spelled wrong and daddy was undefined):

# file of identifiers to load:
foo="bar"
dad=lambda daddy:"Happy fathers day "+str(daddy)
myFavoriteNumber=2
# end file

Here is a sample module using execfile to load the identifiers:

# modTest.py load run time identifiers

print 'locals before loading identifier file:'
print locals()

# load the identifier file
execfile('modTest.txt', globals(), locals())

print 'locals after loading identifier file:'
print locals()

# test identifiers:
print 'foo:', foo
print 'dad("daddy")', dad("daddy")
print 'myFavoriteNumber', myFavoriteNumber

# end modTest code

And the result of running the sample:

locals before loading identifier file:
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': 'D:\\Users\\Work\\Documents\\Demonstrations\\modTest.py', '__doc__': None, '__package__': None}
locals after loading identifier file:
{'dad': <function <lambda> at 0x0225F970>, 'myFavoriteNumber': 2, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'D:\\Users\\Work\\Documents\\Demonstrations\\modTest.py', '__package__': None, '__name__': '__main__', 'foo': 'bar', '__doc__': None}
foo: bar
dad("daddy") Happy fathers day daddy
myFavoriteNumber 2

This should do what you want. But be careful.

Richard

-----Original Message----- From: derek riemer
Sent: Saturday, June 20, 2015 7:18 PM
To: pythonvis@xxxxxxxxxxxxx
Subject: [pythonvis] question about converting strings to variables?

Hi,
In python (or any language) is is possible to convert a string to a
variable? For example, if I have something like a file with
foo="bar"
dad=lammbda daddy:"Happy fathers day "+str(daddy)
myFavoriteNumber=2

Could I read these in from a file and get in the computers memory the
variable dad = a function, foo="bar" and so on?
This would be pretty helpful, in being able to actually write compilers,
or simple scripting languages.
How is this type of thing achieved?

Thanks,
Derek
List web page is
//www.freelists.org/webpage/pythonvis

To unsubscribe, send email to
pythonvis-request@xxxxxxxxxxxxx with "unsubscribe" in the Subject field.
List web page is //www.freelists.org/webpage/pythonvis

To unsubscribe, send email to pythonvis-request@xxxxxxxxxxxxx with "unsubscribe" in the Subject field.

Other related posts: