473,406 Members | 2,217 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,406 software developers and data experts.

How to turn a variable name into a string?

I'd like to do something like the following:

a = 1; b = 2; c = None
mylist = [a, b, c]
for my in mylist:
if my is None:
print 'you have a problem with %s' % my #this line is problematic
You have a problem with None
What I want to see in the output is: You have a problem with c


How do I convert a variable name into a string?

thanks!

--
Stewart Midwinter
st*****@midwinter.ca
st***************@gmail.com
Jul 18 '05 #1
11 21698
Stewart Midwinter wrote:
I'd like to do something like the following:

a = 1; b = 2; c = None
mylist = [a, b, c]
for my in mylist:
if my is None:
print 'you have a problem with %s' % my #this line is problematic
You have a problem with None
What I want to see in the output is:You have a problem with c


How do I convert a variable name into a string?


You cannot. In the above example, when you hit
the None item in the list, there is only one None
object in existence, and three different names
"bound" to it: c, my, and the third spot in the
list. (Think of this "bound" thing as being like
strings attaching a variety of names to the item
itself.)

Given the object "None" then, how can Python know
which of the names you intended? More to the
point, by the time you've finished creating the
list mylist, the connection to "c" is long gone.
It is exactly as though you had typed this instead:
mylist = [1, 2, None]

There are doubtless other ways to accomplish what
you are really trying to do (display some sort of
information for debugging purposes?), but with a
contrived example it's a little hard to pick the
best...

By the way, this sort of thing should be well
covered by the FAQ entries, if you read them.
See, for example,
http://www.python.org/doc/faq/progra...e-of-an-object

-Peter
Jul 18 '05 #2
Any given Python object may be bound to multiple names or none at all,
so trying to find the symbol(s) which reference an object is sort of
quixotic.

In fact, you've got None referenced by both "my" and "c" in this
example, and in a more complicated program None will be referenced by
dozens symbols because it's unique [e.g. (a == None, b == None)
necessitates (a is b) == True]

You could try using "is" to match it with something in the namespace,
though. This might do what you want.

def names(thing):
return [name for name,ref in globals().iteritems() if ref is thing]

a = 1; b = 2; c = None

mylist = [a,b,c]
for my in mylist:
if my is None:
print 'you have a problem with %s' % names(my)
-------------

Although it would be much simpler to rewrite your code like this:

a = 1; b = 2; c = None

mylist = ['a','b','c']
for my_name in mylist:
my = eval(my_name)
if my is None:
print 'you have a problem with %s' % my_name

Jul 18 '05 #3
Hi Stewart,

what about the other way, string -> var and not var -> string?

My suggestion:
mylist = ["a", "b", "c"]
for my in mylist:
if locals()[my] == None:
print "you have a problem with %s" % my

Paolo

Stewart Midwinter wrote:
I'd like to do something like the following:

a = 1; b = 2; c = None
mylist = [a, b, c]
for my in mylist:
if my is None:
print 'you have a problem with %s' % my #this line is problematic

You have a problem with None

What I want to see in the output is:
You have a problem with c

How do I convert a variable name into a string?

thanks!

Jul 18 '05 #4
Stewart Midwinter wrote:
I'd like to do something like the following:

a = 1; b = 2; c = None
mylist = [a, b, c]
for my in mylist:
if my is None:
print 'you have a problem with %s' % my #this line is problematic
You have a problem with None

What I want to see in the output is:
How do I convert a variable name into a string?


I think you actually want the opposite:

a = 1; b = 2; c = None
mylist = ['a', 'b', 'c']
for my in mylist:
if globals()[my] is None:
print 'you have a problem with %s' % my
Jul 18 '05 #5
lots of good answers there, and quickly, too!

I can see that I need to explain a bit further what I'm up to.

I have a number of variables (environmental variables, actually), most
of which will have a value. But some may not have been found by
os.environ.get(), so I set those to None. Now, if any of them are None,
the app cannot proceed, so I want to test for this and warn the user.
I could do something like this (actually, there are more than 3 vars):
a = "c:\\programs"
b = "d:\\data"
c = None (result of an assignment after the os.environ.get() returned
a KeyError).
if (a is None) or (b is None) or (c is None):
#do something here
print 'you are missing some env vars'

But, that seemed clumsy to me, so I wanted to do something more
pythonic, hence my previous post. So, any suggestions?

thanks!
S

Jul 18 '05 #6
> c = None (result of an assignment after the os.environ.get()
returned a KeyError).

Why not trap the KeyError?

Jul 18 '05 #7
st***************@gmail.com wrote:
lots of good answers there, and quickly, too!

I can see that I need to explain a bit further what I'm up to.

I have a number of variables (environmental variables, actually), most
of which will have a value. But some may not have been found by
os.environ.get(), so I set those to None. Now, if any of them are None,
the app cannot proceed, so I want to test for this and warn the user.
I could do something like this (actually, there are more than 3 vars):
a = "c:\\programs"
b = "d:\\data"
c = None (result of an assignment after the os.environ.get() returned
a KeyError).
if (a is None) or (b is None) or (c is None):
#do something here
print 'you are missing some env vars'

But, that seemed clumsy to me, so I wanted to do something more
pythonic, hence my previous post. So, any suggestions?

Why not build a list of problematic variables as you assign them?
In this case, you would have
problem_list = [c]

if problem_list != []:
# do something here

etc.

André

Jul 18 '05 #8
Perhaps try something like this?

variables = ['a', 'b', 'c']

defaults = {
'a': 'c:\\programs',
'b': 'd:\\data',
# etc
}

try:
settings = dict([(v, os.environ.get(v, defaults[v])) for v in
variables])
except KeyError, k:
# handle missing variable
print "you have a problem with %s" % k.args[0]

# Now if you really must have these as independent variables
globals().update(settings)

Jul 18 '05 #9
On 11 Mar 2005 12:39:30 -0800, "st***************@gmail.com" <st***************@gmail.com> wrote:
lots of good answers there, and quickly, too!

I can see that I need to explain a bit further what I'm up to.

I have a number of variables (environmental variables, actually), most
of which will have a value. But some may not have been found by
os.environ.get(), so I set those to None. Now, if any of them are None,
the app cannot proceed, so I want to test for this and warn the user.
I could do something like this (actually, there are more than 3 vars):
a = "c:\\programs"
b = "d:\\data"
c = None (result of an assignment after the os.environ.get() returned
a KeyError).
if (a is None) or (b is None) or (c is None):
#do something here
print 'you are missing some env vars'

But, that seemed clumsy to me, so I wanted to do something more
pythonic, hence my previous post. So, any suggestions?

If you require a specific set of environment variables to be defined,
why don't you create an object that loads them and validates itself
in the process? E.g.,
import os
class MyEnv(dict): ... def __init__(self, required=''):
... for name in required.split():
... self[name] = os.environ.get(name)
... if None in self.values():
... raise ValueError, 'You are missing some env vars: %r' % [k for k,v in self.items() if v is None]
... __getattr__ = dict.__getitem__
... myenv = MyEnv('TMP OS')
myenv {'TMP': 'v:\\TEMP', 'OS': 'Windows_NT'}

The __getattr__ assignment lets you access the keys as attributes if you want:
myenv.TMP 'v:\\TEMP'

If you try to init with some unknown env variable name, it complains:
me2 = MyEnv('TMP OS unknown')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in __init__
ValueError: You are missing some env vars: ['unknown']

If you have spaces in your environment names (possible?) that would be nasty and
you would have to change the "required" __init__ parameter to split on something other than spaces.
You could arrange for case-insensitivity if you liked. And if you really wanted
to have local or global bindings for your env names, you could easily do that too,
but e.g., myenv.XXX seems like a readable way to group things together.

Regards,
Bengt Richter
Jul 18 '05 #10
> In fact, you've got None referenced by both "my" and "c" in this
example, and in a more complicated program None will be referenced by
dozens symbols because it's unique [e.g. (a == None, b == None)
necessitates (a is b) == True]


Even worse: freshly started 2.2 interpreter:
sys.getrefcount(None)

216

TJR

Jul 18 '05 #11
André Roberge wrote:
st***************@gmail.com wrote:
I have a number of variables (environmental variables, actually), most
of which will have a value. But some may not have been found by
os.environ.get(), so I set those to None. Now, if any of them are None,
the app cannot proceed, so I want to test for this and warn the user.
I could do something like this (actually, there are more than 3 vars):
a = "c:\\programs"
b = "d:\\data"
c = None (result of an assignment after the os.environ.get() returned
a KeyError).
if (a is None) or (b is None) or (c is None):
#do something here
print 'you are missing some env vars'
But, that seemed clumsy to me, so I wanted to do something more
pythonic, hence my previous post. So, any suggestions?


How about this:

try:
mumble = os.environ['TMP']
babble = os.environ['Path']
frobotz = os.environ['NotThere']
jangle = int(os.environ['WEIGHT'])
...
except KeyError, e:
print 'Mising env var %r. Fix it and try again' % e.args
raise SystemExit

--Scott David Daniels
Sc***********@Acm.Org
Jul 18 '05 #12

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

Similar topics

8
by: manish | last post by:
I have created a function, it gives more readability compared to the print_r function. As of print_r, it works both for array or single variable. I just want to add in it, the opton to view the...
14
by: pl | last post by:
Hi all, I followed the mails entitled 'How to turn a variable name into a string?' in march 2005 posts as I have a similar problem. I have to get some list variable names at some point in my...
11
by: Pete Mahoney | last post by:
I am currently working on an ASP page where I create a lot of different check boxes. I have some checkboxes that are Windows platforms and some that are solaris platforms. I want a control...
10
by: cpp | last post by:
I am trying to find out how to assign the name of a variable (aka identifier) given a string for this name. For example: string s = "whatever"; How can I obtain the following expression:...
6
by: Raed Sawalha | last post by:
i have the following case a MyClass class has method with 2 arguments as void SetProp(string varname,string varvalue); in MyClass i have following members string...
45
by: Zytan | last post by:
Shot in the dark, since I know C# doesn't have macros, and thus can't have a stringizer operator, but I know that you can get the name of enums as strings, so maybe you can do the same with an...
6
by: Bora Ji | last post by:
Please help me to creating dynamic VARIABLE in java, with predefined name.
11
by: mfglinux | last post by:
Hello to everybody I would like to know how to declare in python a "variable name" that it is in turn a variable In bash shell I would wrote sthg like: for x in `seq 1 3` do M$i=Material(x)...
2
by: X l e c t r i c | last post by:
Here: http://bigbangfodder.fileave.com/res/sandr.html I'm trying to use string.replace() for a basic search and replace form using textarea values as the regexp and replacement values for...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.