Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Dynamically set variables? (http://www.programmingforums.org/showthread.php?t=10688)

titaniumdecoy Jul 11th, 2006 7:51 PM

Dynamically set variables?
 
Say I import another Python script into the Python script I'm working on. I want to be able to set variables in that file, OR in the file I'm working in, by passing a single variable. For example:

:

import thing

def set_variable(cls):
      cls.new_variable = "cheese"

set_variable(thing)
set_variable(self) # This doesn't work!

print thing.new_variable
print new_variable # I want both of these to print "cheese"!


Arevos Jul 11th, 2006 8:09 PM

Hmm... Perhaps something like:
:

def set_variable(name, value, obj = None):
    if obj is None:
        globals()[name] = value
    else:
        vars(obj)[name] = value

To set a variable in the local module, omit the obj argument.


All times are GMT -5. The time now is 12:51 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC