473,396 Members | 1,966 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Create a variable "on the fly"

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.

--
Please remove the "x-" if replying to sender.
Jul 27 '05 #1
11 4152
Paul D.Smith wrote:
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
Jul 27 '05 #2
Dan
> make_variable('OSCAR', 'the grouch');
print OSCAR;


Try using "setattr". (It's in __builtins__; you don't have to import
anything.)
print setattr.__doc__

setattr(object, name, value)

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

--
If builders built buildings the way programmers write programs,
the first woodpecker that came along would destroy civilization.
- Original author unknown
Jul 27 '05 #3
Paul D.Smith wrote:
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
Jul 27 '05 #4
PythonWin 2.3.5 (#62, Feb 9 2005, 16:17:08) [MSC v.1200 32 bit
(Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond (mh******@skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
locals()['OSCAR'] = 'the grouch'
OSCAR 'the grouch'


Jul 27 '05 #5
Paul D.Smith wrote:
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...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 27 '05 #6
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

Jul 27 '05 #7
Hi !

Try :

OSCAR='the grouch'
print OSCAR
useless to thank me

Michel Claveau
Jul 27 '05 #8
Bruno,

FYI, notes in-line...

Cheers,
Paul DS
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...


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.
Jul 28 '05 #9
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
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Jul 28 '05 #10
Paul D.Smith wrote:
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
Jul 28 '05 #11
Paul D.Smith wrote:
... 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
Sc***********@Acm.Org
Jul 28 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
by: Chris Krasnichuk | last post by:
hello, Does anyone know how I make php work on "my" computer? I made a mistake in my last post so I fixed it here. Chris
5
by: Alfonso Morra | last post by:
Hi, I've written a very simple Simpleton design pattern class template. This was supposed to illustrate a point. Although it compiles without nay errors, I get link errors (unresolved external),...
2
by: George Marsaglia | last post by:
I have a set of, say, 2000 points in the 8-dimensional simplex S={(x_1,x_2,...,x_8),x_1+x_2+...+x_8=1, x's>=0}. To help analyze that 8-dimensional set, I wish to project the set of points onto...
3
by: Ahmed Ayoub | last post by:
i forgot how to create Textboxes & Label Dynamically. Meaning, i want to make them .. initialize their position .. and view them and interact with them.
0
by: Ronald Snelgrove | last post by:
To All: I am a newbie to VB.net and am writing an application in VB.net in which I successfully create an Excel sheet, tabulate and format some data on a sheet titled "summarySheet". A...
3
by: gregory_may | last post by:
According to this article, I cant change "CanStop" on the fly!!! ...
2
by: Chuck Anderson | last post by:
I have a web page/script that displays image files residing on disk. I do not know what size they are (in pixels), so I want to be able to resize an image if it is bigger than the limit I allow...
6
by: OAM | last post by:
Hi Is it possible to add and remove tabs "on the fly" ? Anybody have a (ajax...) script to do this ? Thanks Olivier.
3
by: Evan | last post by:
Hello, one of my PC is window system, and in "control panel -Network Connections", I can see some network connections such as PPPOE or VPN which I created by click "create a new connection". ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.