473,574 Members | 2,450 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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*****@midwint er.ca
st************* **@gmail.com
Jul 18 '05 #1
11 21714
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().iteri tems() 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:\\progra ms"
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:\\progra ms"
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().updat e(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:\\progra ms"
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

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

Similar topics

8
2452
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 variable name for the case of non array variables. Also I want to show the array name. Is there any way that the variable name that is passed to the...
14
2117
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 program. So I ended up looking into globals() to get them with a small function like this: #!/usr/bin/python
11
29792
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 checkbox over the Windows ones to turn them all on or all off, and the same with the solaris. One of the control check boxes looks something like this:...
10
3464
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: double whatever = 4; As you can see, I want the variable name to be taken from a string's value.
6
12749
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 stdname,stddate,stdbirth,stdloc from other class i created object from MyClass ,
45
13576
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 ordinary variable (like an int) somehow. Is it possible? int.ToString() returns the value of the int as a string, not the name, so I am thinking...
6
13754
by: Bora Ji | last post by:
Please help me to creating dynamic VARIABLE in java, with predefined name.
11
2241
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) #Material is a python class done
2
11670
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 string.replace(). When I tried to use the textarea variable name for regexp it didn't work as I thought it would. For example:
0
7794
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7710
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8040
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8225
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7800
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6437
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3738
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3745
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1051
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.