Create a variable "on the fly"

P

Paul D.Smith

Can Python create a variable "on-the-fly". For example I would like
something like...

make_variable('OSCAR', 'the grouch');
print OSCAR;

....to output...

the grouch

Anything like this in Python?

And in case anyone is interested, I want to instantiate a set of variables
based on environment variables without using os.environ everywhere by having
a look instantiate Python variables of the appropriate type.

Thanks,
Paul DS.
 
D

Dan

make_variable('OSCAR', 'the grouch');
print OSCAR;

Try using "setattr". (It's in __builtins__; you don't have to import
anything.)
setattr(object, name, value)

Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
 
D

Do Re Mi chel La Si Do

Hi !

Try :

OSCAR='the grouch'
print OSCAR


useless to thank me

Michel Claveau
 
B

bruno modulix

Paul said:
Can Python create a variable "on-the-fly". For example I would like
something like...

make_variable('OSCAR', 'the grouch');
print OSCAR;

...to output...

the grouch

Anything like this in Python?

The bad news is that yes, there is something "like this" in Python.

The good news is that I won't tell you more about it, since it's a very
bad practice(tm). The good practice is to put your vars in a dict.
And in case anyone is interested, I want to instantiate a set of variables
based on environment variables without using os.environ everywhere

env = os.environ

Now you just have to look at env['MY_ENV_VAR'] !-)
by having
a look instantiate Python variables of the appropriate type.

What do you mean "of the appropriate type" ? You want to typecast (eg.
from string to numeric) ? Then you need to know what env var must be
casted to what type ? Then you don't need to create variables 'on the fly' ?

I must have missed something...
 
P

Paolino

Paul said:
Can Python create a variable "on-the-fly". For example I would like
something like...

make_variable('OSCAR', 'the grouch');
print OSCAR;

...to output...
Python has only 'on the fly' variables and ';' is not used for one
expression in one line.


Probably the tutorial is good to be read also.

Paolino





___________________________________
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB
http://mail.yahoo.it
 
P

Paolino

Paul said:
Can Python create a variable "on-the-fly". For example I would like
something like...

make_variable('OSCAR', 'the grouch');
print OSCAR;

...to output...
Python has only 'on the fly' variables and ';' is not used for one
expression in one line.


Probably the tutorial is good to be read also.

Paolino
 
W

Willem Broekema

Steve M:
locals()['OSCAR'] = 'the grouch'
OSCAR 'the grouch'

Use "globals", not "locals":

globals()['OSCAR'] = 'the grouch'

because <http://www.python.org/doc/current/lib/built-in-funcs.html>
states:

locals()
Update and return a dictionary representing the current local symbol
table. Warning: The contents of this dictionary should not be
modified; changes may not affect the values of local variables used
by the interpreter.

Function globals() is not subject to this restriction.


- Willem
 
P

Paul D.Smith

Bruno,

FYI, notes in-line...

Cheers,
Paul DS
What do you mean "of the appropriate type" ? You want to typecast (eg.
from string to numeric) ? Then you need to know what env var must be
casted to what type ? Then you don't need to create variables 'on the fly' ?

I must have missed something...

Good point - my Python "nomenclature" is still in its infancy. The
background is that I've inherited some historical Python scripts that need
to be configured from a bash shell script (as these Python scripts are being
integrated into a bigger system driven by shell scripts and with a
pre-existing single "point-of-configuration") instead of the existing
Pything config script. The existing Python script configures these
parameters thus...

PARM1='Fred'
PARM2=12
....

So I could so the following...

PARM1=os.environ['PARM1']
PARM2=os.environ['PARM2']
....

The problem is that this config file is almost certainly not complete (as
the complete integration of all scripts has not been done) and I don't want
to spend my life tweaking not one config file (the shell script), but two
(the shell script and the Python script).

Now I'm helped because in fact the parameters have a common format e.g.

MY_PARM1...
MY_PARM2...

so I can define shell environment variables with the same names and then
look for any parameter defined in the shell and named "MY_..." and
instantiate the Python variable from that.

What I'm left with is the following...

1. A shell script which I maintain.
2. A simple Python config which searches for all shell environment variables
named "MY_..." and instantiates then as Python variables.
3. Historical scripts that run without me needing to spend time hunting down
all the config variables and replacing them with os.environ['MY_...'].

Agreed that long term this is not good practice, but short term it's a time
save.
 
S

Sybren Stuvel

Paul D.Smith enlightened us with:
The background is that I've inherited some historical Python scripts
that need to be configured from a bash shell script [...] instead of
the existing Pything config script. [...] The problem is that this
config file is almost certainly not complete [...] and I don't want
to spend my life tweaking not one config file (the shell script),
but two (the shell script and the Python script).

So basically you want environment variables to be able to alter Python
variables. This is not a smart move. It's the same as the
'register_globals' functionality in PHP. Read
http://us2.php.net/register_globals for more information.
2. A simple Python config which searches for all shell environment
variables named "MY_..." and instantiates then as Python variables.

Why don't you just copy all MY_... environment variables from
os.environ to the dict which holds your configuration? Or are you
storing your entire configuration in global variables? A dict would be
a much cleaner and more extendible solution.

Sybren
 
S

Steven Bethard

Paul said:
2. A simple Python config which searches for all shell environment variables
named "MY_..." and instantiates then as Python variables.

my_vars = dict((k, v)
for k, v in os.environ.iteritems()
if k.startswith('MY_'))
globals().update(my_vars)

If you ever refactor the code, I'd suggest writing a single
configuration file instead of setting environment variables, and reading
that configuration file in each script that needs it. Generally I've
found that relying on environment variables being set is hard to
maintain and a real pain when you have to move to a new system.

STeVe
 
S

Scott David Daniels

Paul said:
... What I'm left with is the following...
1. A shell script which I maintain.
2. A simple Python config which searches for all shell environment variables
named "MY_..." and instantiates then as Python variables.
3. Historical scripts that run without me needing to spend time hunting down
all the config variables and replacing them with os.environ['MY_...'].

Suppose you have a module named 'MY', with MY.py as:

import os
_globals = globals()
for _name, _entry in os.environ.iteritems():
if _name.startswith('MY_'):
try:
_entry = int(_entry)
except ValueError:
try:
_entry = float(_entry)
except ValueError:
pass
_globals[_name[3 :]] = _entry

then, wherever your python scripts use MY_XYZ, you begin the script
with "import MY" and change every "MY_XYZ" to "MY.XYZ".


--Scott David Daniels
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top