473,511 Members | 14,975 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

implicit variable declaration and access

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
16 3023
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
In article <1Q*******************@bignews5.bellsouth.net>,
Christopher Subich <sp****************@block.subich.spam.com> wrote:
Jul 19 '05 #17

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

Similar topics

3
43287
by: Jason | last post by:
Hi, Im running windows xp pro and compiling using dev c++ 4. I have the following situation: #include <iostream> #include <string> using namespace std; int main() {
59
3139
by: Chris Dunaway | last post by:
The C# 3.0 spec (http://msdn.microsoft.com/vcsharp/future/) contains a feature called "Implicitly typed local variables". The type of the variable is determined at compile time based on the...
36
3589
by: Chad Z. Hower aka Kudzu | last post by:
I have an implicit conversion set up in an assembly from a Stream to something else. In C#, it works. In VB it does not. Does VB support implicit conversions? And if so any idea why it would work...
3
1482
by: Earthlink | last post by:
This is best explained by looking at the comments in the sample code below. Is this a VB.NET bug? Option Strict On Public Class Class1 End Class Public Class Class2 : Inherits Class1
20
2434
by: srinivasarao_moturu | last post by:
template<class TClass ABC { public : void SetValue(T k) { val = k; } private: T val; };
22
6162
by: Nathan Laff | last post by:
so, myself and the other developers i work with were looking at the v3.0 specifications. extensions look great, buy what is the point of implicit variables with the 'var' type? before you bash...
5
2706
by: johanatan | last post by:
Does anyone know the reasons for the lack of an implicit casting operator in any greater depth than: A. Automatic conversion is believed to be too error prone. (from the FAQ at the bottom of:...
1
11849
NeoPa
by: NeoPa | last post by:
Problem Description : In VBA there is an option to enforce declaration of variables in your code. With this set, any reference to a variable that has not been previously declared (Dim; Private;...
5
3311
by: DanielJohnson | last post by:
I call a function which is named as func_name in file /source/folderA/ fileA.c. The actual function definition is in /source/folderB/fileB.c. And I get this error. warning: implicit...
0
7252
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
7153
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
7371
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
7432
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7517
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
4743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1583
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
452
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.