implicit variable declaration and access

A

Ali Razavi

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 ?
 
A

Ali Razavi

Ali said:
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)
 
B

Benji York

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:
.... pass
....
8

code = 'print ' + x
exec(code)

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

HTH
 
T

Tom Anderson

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
 
P

Peter Dembinski

[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 ;)
 
A

Ali Razavi

Tom said:
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.
 
T

Tom Anderson

[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
 
S

Steven D'Aprano

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>
 
C

Cameron Laird

[snap]
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.
 
C

Christopher Subich

Cameron said:
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.
 
T

Tom Anderson

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
 
S

Scott David Daniels

Tom said:
... 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
(e-mail address removed)
 
A

Ali Razavi

Steven said:
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!
 
T

Tom Anderson

Tom said:
... 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:
.... locals()["myvar"] = 42
.... print myvar
....Traceback (most recent call last):
File "<stdin>", line 1, in ?

My bad.

tom
 
C

Cameron Laird

.
.
.
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.

1. If you know enough to ask the question, you're
a consenting adult, and equipped to deal with
the consequences.
2. Hey, that's the whole *idea* of an extension
language. Go forth and Python happily, even
exec() with righteousness.
3. But Python *is* an unsafe language in such
uses--one of which I'm exceptionally fond, but
undeniably unsafe.
 

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

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top