By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,235 Members | 1,011 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,235 IT Pros & Developers. It's quick & easy.

implicit variable declaration and access

P: n/a
Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?
Jul 19 '05 #1
Share this Question
Share on Google+
16 Replies


P: n/a
Ali Razavi wrote:
Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?

Got it! use higher order functions like Lisp!

code = x + '= 0'
exec(code)

code = 'print ' + x
exec(code)

Jul 19 '05 #2

P: n/a
Ali Razavi wrote:
Ali Razavi wrote:
Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
Got it! use higher order functions like Lisp!
No, you use higher order functions like Python. :)
code = x + '= 0'
exec(code)
You should generally stay away from exec for lots of reasons. I won't
elaborate but a search of this group would be informative.

If you want to affect the globals (which you probably don't) you can
do this:
x = 'my_var'
globals()[x] = 7
my_var 7

If you want to set an attribute on a particular object (which is more
likely), you can do this:
class C: .... pass
.... c = C()
setattr(c, x, 8)
c.my_var 8
code = 'print ' + x
exec(code)


Getting the value would be like this, respectively:
print globals()[x] 7 getattr(c, x)

8

HTH
--
Benji York
Jul 19 '05 #3

P: n/a
Benji York <be***@benjiyork.com> writes:

[snap]
code = x + '= 0'
exec(code)


You should generally stay away from exec for lots of reasons.


Code 'refactorizability' is one of them.
Jul 19 '05 #4

P: n/a
On Mon, 13 Jun 2005, Ali Razavi wrote:
Is there any reflective facility in python that I can use to define a
variable with a name stored in another variable ?

like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?


Are you absolutely sure you want to do this?

tom

--
The MAtrix had evarything in it: guns, a juimping off teh walls, flying guns, a bullet tiem, evil computar machenes, numbers that flew, flying gun bullets in slowar motian, juimping into a gun, dead police men, computar hackeing, Kevin Mitnick, oven trailers, a old womans kitchen, stairs, mature women in clotheing, head spark plugs, mechaanical squids, Japaneseses assasins, tiem traval, volcanos, a monstar, slow time at fastar speed, magic, wizzards, some dirty place, Kung Few, fighting, a lot of mess explodsians EVARYWHERE, and just about anything else yuo can names!
Jul 19 '05 #5

P: n/a
Tom Anderson <tw**@urchin.earth.li> writes:

[snap]
The MAtrix had evarything in it: guns, a juimping off teh walls,
flying guns, a bullet tiem, evil computar machenes, numbers that
flew, flying gun bullets in slowar motian, juimping into a gun, dead
police men, computar hackeing, Kevin Mitnick, oven trailers, a old
womans kitchen, stairs, mature women in clotheing, head spark plugs,
mechaanical squids, Japaneseses assasins, tiem traval, volcanos,
a monstar, slow time at fastar speed, magic, wizzards, some dirty
place, Kung Few, fighting, a lot of mess explodsians EVARYWHERE,
and just about anything else yuo can names!


....with greetings to Carnivore ;)
Jul 19 '05 #6

P: n/a
Tom Anderson wrote:
On Mon, 13 Jun 2005, Ali Razavi wrote:
Is there any reflective facility in python that I can use to define a
variable with a name stored in another variable ?

like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?

Are you absolutely sure you want to do this?

tom

Have you ever heard of meta programming ?
I guess if you had, it wouldn't seem this odd to you.
Jul 19 '05 #7

P: n/a
On Mon, 13 Jun 2005, Peter Dembinski wrote:
Tom Anderson <tw**@urchin.earth.li> writes:

[snap]
The MAtrix had evarything in it: guns, a juimping off teh walls, flying
guns, a bullet tiem, evil computar machenes, numbers that flew, flying
gun bullets in slowar motian, juimping into a gun, dead police men,
computar hackeing, Kevin Mitnick, oven trailers, a old womans kitchen,
stairs, mature women in clotheing, head spark plugs, mechaanical
squids, Japaneseses assasins, tiem traval, volcanos, a monstar, slow
time at fastar speed, magic, wizzards, some dirty place, Kung Few,
fighting, a lot of mess explodsians EVARYWHERE, and just about anything
else yuo can names!


...with greetings to Carnivore ;)


Ah, poor old Carnivore. I sort of feel sorry for it, trying to find
terrsts in the midst of an internet populated by a hojillion people
jabbering about, well, everything, really. Maybe the FBI should hook up
with the SETI@home guys. After all, if they can find intelligence in outer
space, surely they can find it on the internet?

Actually, on second thoughts ...

tom

--
When I see a man on a bicycle I have hope for the human race. -- H. G. Wells
Jul 19 '05 #8

P: n/a
On Mon, 13 Jun 2005 12:18:31 -0400, Ali Razavi wrote:
Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?


Any time you find yourself wanting to indirectly define variables like
this, the chances are you would get better results (faster, less security
risks, easier to maintain, easier to re-factor and optimise, more
readable) if you change the algorithm.

Instead of:

x = "myVarName"
create_real_variable(x, some_value)
print myVarName

why not do something like this:

data = {"myVarName": some_value}
print data["myVarName"]

It is fast, clean, easy to read, easy to maintain, no security risks from
using exec, and other Python programmers won't laugh at you behind your
back <smiles>
--
Steven

Jul 19 '05 #9

P: n/a
In article <87************@hector.domek>,
Peter Dembinski <pd***@gazeta.pl> wrote:
Benji York <be***@benjiyork.com> writes:

[snap]
code = x + '= 0'
exec(code)


You should generally stay away from exec for lots of reasons.


Code 'refactorizability' is one of them.


There's an affirmative way to express this that I can't now make
the time to generate. Yes, you're both right that, as popular as
some make out such coding is in Lisp (and Perl and PHP), the per-
ception that there's a need for it generally indicates there's a
cleaner algorithm somewhere in the neighborhood. In general,
"application-level" programming doesn't need exec() and such.

PyPy and debugger writers and you other "systems" programmers
already know who you are.

My own view is that refactorizability is one of the secondary
arguments in this regard.
Jul 19 '05 #10

P: n/a
In article <d8**********@rumours.uwaterloo.ca>,
Ali Razavi <ar*****@swen.uwaterloo.ca> wrote:
Tom Anderson wrote:
On Mon, 13 Jun 2005, Ali Razavi wrote:
Is there any reflective facility in python that I can use to define a
variable with a name stored in another variable ?

Jul 19 '05 #11

P: n/a
Cameron Laird wrote:
cleaner algorithm somewhere in the neighborhood. In general,
"application-level" programming doesn't need exec() and such.

PyPy and debugger writers and you other "systems" programmers
already know who you are.


Out of curiosity, where would you classify interpreters for secondary
app-specific programming languages? Specifically, mud-client stored
procedures (triggers, timed events) seem to correspond very naturally to
generating the python code required to execute them in advance, then
compile()ing and storing the compiled code for repeated execution.
Jul 19 '05 #12

P: n/a
On Mon, 13 Jun 2005, Ali Razavi wrote:
Tom Anderson wrote:
On Mon, 13 Jun 2005, Ali Razavi wrote:
Is there any reflective facility in python that I can use to define a
variable with a name stored in another variable ?

like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string stored
in x. And how can I access that implicitly later ?


Are you absolutely sure you want to do this?


Have you ever heard of meta programming ? I guess if you had, it
wouldn't seem this odd to you.


Oh, i have. It's just that i've also seen about a billion posts from
novice programmers asking exactly that question, when it turns out what
they really want is a dictionary, or sometimes a list. If that was the
case, answering your question would not be solving your problem, an i'd
rather solve your problem.

If it's not, try:

x = "myVarName"
y = "myVarValue"
locals()[x] = y

What did you mean by "And how can I access that implicitly later?"?

tom

--
I content myself with the Speculative part [...], I care not for the Practick. I seldom bring any thing to use, 'tis not my way. Knowledge is my ultimate end. -- Sir Nicholas Gimcrack
Jul 19 '05 #13

P: n/a
Tom Anderson wrote:
... If it's not, try:
x = "myVarName"
y = "myVarValue"
locals()[x] = y


Sorry, this works with globals(), but not with locals().
There isn't a simple way to fiddle the locals (the number
is determined when the function is built).

I do, however, agree with you about what to use. I use:
class Data(object):
def __init__(self, **kwargs):
for name, value in kwargs.iteritems():
setattr(self, name, value)
def __repr__(self):
return '%s(%s)' % (type(self).__name__, ', '.join(
['%s=%r' % (name, getattr(self, name))
for name in dir(self) if name[0] != '_']))

When I want to fiddle with named values.
el = Data(a=5, b='3')
el.c = el.a + float(el.b)
setattr(el, 'other', getattr(el, 'a') + getattr(el, 'c'))
el

--Scott David Daniels
Sc***********@Acm.Org
Jul 19 '05 #14

P: n/a
Steven D'Aprano wrote:
On Mon, 13 Jun 2005 12:18:31 -0400, Ali Razavi wrote:

Is there any reflective facility in python
that I can use to define a variable with a
name stored in another variable ?
like I have :
x = "myVarName"

what can I do to declare a new variable with the name of the string
stored in x. And how can I access that implicitly later ?

Any time you find yourself wanting to indirectly define variables like
this, the chances are you would get better results (faster, less security
risks, easier to maintain, easier to re-factor and optimise, more
readable) if you change the algorithm.

Instead of:

x = "myVarName"
create_real_variable(x, some_value)
print myVarName

why not do something like this:

data = {"myVarName": some_value}
print data["myVarName"]

It is fast, clean, easy to read, easy to maintain, no security risks from
using exec, and other Python programmers won't laugh at you behind your
back <smiles>

I ain't writing a real program, just summarizing a few languages
(Python, Smalltalk, Ruby, ...) meta programming facilities and compare
them with each other, it will only be an academic paper eventually. Thus
I am only trying out stuff, without worrying about their real world
consequences. And yes you are right, I am not a Python programmer, well
to be honest, I am not a real "any language" programmer, as I have never
written any big programs except my school works, and I don't even intend
to become one, Sorry it's just too boring and repetitive, there are much
more exciting stuff for me in computer engineering and science than
programming, so I will leave the hard coding job to you guys and let you
laugh behind the back of whoever you want!
Have a good one!

Jul 19 '05 #15

P: n/a
On Tue, 14 Jun 2005, Scott David Daniels wrote:
Tom Anderson wrote:
... If it's not, try:
x = "myVarName"
y = "myVarValue"
locals()[x] = y


Sorry, this works with globals(), but not with locals().


Oh, weird. It works when i tried it.

Aaaah, i only tried it at the interactive prompt. If i actually try
writing a function which does, that, yes, i get:
def foo(): .... locals()["myvar"] = 42
.... print myvar
.... foo() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in foo
NameError: global name 'myvar' is not defined


My bad.

tom

--
Gens una summus.
Jul 19 '05 #16

P: n/a
In article <1Q*******************@bignews5.bellsouth.net>,
Christopher Subich <sp****************@block.subich.spam.com> wrote:
Jul 19 '05 #17

This discussion thread is closed

Replies have been disabled for this discussion.