473,386 Members | 1,828 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,386 software developers and data experts.

Getting current variable name

pl
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

l1 = ['r', 'r', 't']
l2 = ['r', 't', 't']
l3 = ['t', 't', 't'] # Two equivalent lists but...
l4 = ['t', 't', 't'] # with different names

def nameofObj(obj):
# print locals()
globdict = globals()
var = globals().keys()
for i in var :
if globdict[i] == obj:
print i
print '-'*20 ,'\n'
nameofObj(l1)

print '-'*20 ,'\n'
map(nameofObj, [l1, l2, l3, l4])

--------------------------------------------------------------------
If you try this, with 2 equivalent lists
(here l3 and l4 when using map) the function will return both
possibilities l3 and l4 which I understand.
So this solution is limitated to unique lists, unfortunately I do have
equivalent lists in my case...

The problem comes from the fact that locals() and globals() have
in common their values but not the keys which then can't be tested.

The only solution I see would be to link the list and its name (in
a dictionary for instance) but that does not sound elegant to me?
If you guys can help a newbie...

Thank you
--
------------------------------------------------------------------
| Patrick LADAM | |
| Laboratoire CSSB | THE BIG BANG THEORY: |
| UFR SMBH | |
| 74 rue Marcel Cachin | In the begining there was |
| 93017 Bobigny CEDEX | nothing at all. |
| >>> NEW e-mail: <<< | |
| la***@smbh.smbh.univ-paris13.fr | Then, it exploded... |
| Tel: 01 48 38 77 26 / 76 85 | |
| Fax: 01 48 38 77 77 | |
------------------------------------------------------------------


Jul 18 '05 #1
14 2102
pl wrote:
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: [...] var = globals().keys()
for i in var :
if globdict[i] == obj:
print i


Use 'is' instead of '=='. This will return true if the arguments are the
same object:
l1 = [1, 2, 3]
l2 = [1, 2, 3]
l1 == l2 True l1 is l2

False

Daniel
Jul 18 '05 #2
pl wrote:
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

l1 = ['r', 'r', 't']
l2 = ['r', 't', 't']
l3 = ['t', 't', 't'] # Two equivalent lists but...
l4 = ['t', 't', 't'] # with different names

def nameofObj(obj):
# print locals()
globdict = globals()
var = globals().keys()
for i in var :
if globdict[i] == obj:
print i
print '-'*20 ,'\n'
nameofObj(l1)

print '-'*20 ,'\n'
map(nameofObj, [l1, l2, l3, l4])


What is the problem you're trying to solve here? Looking up the names
of an object is not usually something you want to do. If you provide a
little more detail on your use case, we might be able to help you
refactor this code.

STeVe
Jul 18 '05 #3
Ron
pl wrote:
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.


Use the locals() function instead of globals().

Thanks by the way, I was wondering how to do this also, your post, and
Daniel pointing out 'is', helped me work this out. There should be an
easier way that doesn't require stepping though the name list.

This doesn't use lists in the same way, but I think it answers your
question.

def getvinfo(vars, v):
"""
vars is locals()
v is [varable]
Use an one item list to pass single varables by reference.
"""
for n in vars.keys():
if vars[n] is v[0]:
return n, v[0], type(v[0])

a = 101
b = 2.3
c = True

print getvinfo(locals(), [a])
print getvinfo(locals(), [b])
print getvinfo(locals(), [c])

('a', 101, <type 'int'>)
('b', 2.2999999999999998, <type 'float'>)
('c', True, <type 'bool'>)
This could be useful for printing error messages and debugging info.

Ronald Adam
Jul 18 '05 #4
Ron wrote:
def getvinfo(vars, v):
"""
vars is locals()
v is [varable]
Use an one item list to pass single varables by reference.
"""
for n in vars.keys():
if vars[n] is v[0]:
return n, v[0], type(v[0])

a = 101
b = 2.3
c = True

print getvinfo(locals(), [a])
print getvinfo(locals(), [b])
print getvinfo(locals(), [c])
>>> ('a', 101, <type 'int'>)
('b', 2.2999999999999998, <type 'float'>)
('c', True, <type 'bool'>)


Are you sure that you really need that single-element list?
def getvinfo2(vars, v): .... for n in vars.keys():
.... if vars[n] is v:
.... return n, v, type(v)
.... getvinfo2(locals(), a) ('a', 1, <type 'int'>) getvinfo2(locals(), b) ('b', 2.2999999999999998, <type 'float'>)


Now, making that second parameter a list would enable you to do this
for multiple local names with a single call, but getvinfo() doesn't
try to do that...

Don't forget, in Python, all names are references. You only have to
be careful when you start re-binding names...

Jeff Shannon

Jul 18 '05 #5
> There should be an easier way that doesn't require stepping though
the name list.

Trying to find names bound to a particular object is a /very/ strange
thing to want to do in Python. If this is for anything more than
debugging diagnostics, it's probably better to use a dictionary
explicitly for your variables and not muck around with global or local
namespace.

Jul 18 '05 #6
Ron
Jeff Shannon wrote:

Are you sure that you really need that single-element list?
No I'm not sure, I thought I found a concdition where it made a
difference while playing with it, but I don't recall just what
circumstance it was?
Don't forget, in Python, all names are references. You only have to be
careful when you start re-binding names...


Since more than one name can bind to an object, this would be better.
def getvinfo( vars, v ):
names = []
for n in vars.keys():
if vars[n] is v:
names.append(n)
return names, v, type(v)

a = [2]
b = [2]
c = b

print getvinfo( locals(), a )
print getvinfo( locals(), b )
print getvinfo( locals(), c )
(['a'], [2], <type 'list'>)
(['b', 'c'], [2], <type 'list'>)
(['b', 'c'], [2], <type 'list'>)






Jul 18 '05 #7
All names have been removed to protect the guilty :-)

In an earlier post, I read a piece of code:
l1 = [1, 2, 3]
l2 = [1, 2, 3]
l1 == l2 True

I immediately gave a double-take: 11 equals 12? What
gives? Can you re-bind literals in Python???
11 = [1, 2, 3]

SyntaxError: can't assign to literal

And then it hit me. That wasn't eleven and twelve, the
variable names were lowercase L with the digits one and
two appended.

Imagine running a long piece of code on some test data
and finding an off-by-one bug which you think is on the
line "myvalue = something + l1". You change the eleven
to 12 and now the code works on your test data but not
for anything else.

If you have access to a syntax-aware editor, it will
help avoid such problems, but better to avoid them in
the first place. You might be reading code printed in
black and white on dead tree one day.

Lesson the first: remember that in many fonts, zero and
capital O are identical, as are lowercase L and 1 and
sometimes even uppercase I. Avoid using names which can
be easily confused for literals or for each other.

What are some of other people's favourite tips for
avoiding bugs in the first place, as opposed to finding
them once you know they are there?
--
Steven
Jul 18 '05 #8
This struck me also when I first saw this post. It reminded me of a
body of code I inherited at a former job, that I had to help untangle.
The code was filled with two key variables: t_1 and t_l. Printing out
the source in a Courier font made these two vars completely
indistinguishable, and it took a while to realize that there even were
two different vars. After globally replacing them with t_first and
t_last, things became a lot clearer!

-- Paul

Jul 18 '05 #9
Steve wrote:
[an anecdote on distinguishing l1 and 11] What are some of other people's favourite tips for
avoiding bugs in the first place, as opposed to finding
them once you know they are there?


There's a good book on this topic - Writing Solid Code.

Andrew
da***@dalkescientific.com

Jul 18 '05 #10
On Wed, 30 Mar 2005 07:02:57 GMT, Andrew Dalke <da***@dalkescientific.com> wrote:
Steve wrote:
[an anecdote on distinguishing l1 and 11]

What are some of other people's favourite tips for
avoiding bugs in the first place, as opposed to finding
them once you know they are there?


There's a good book on this topic - Writing Solid Code.


And there's an excellent website showing what *not* to do:
http://mindprod.com/unmain.html

The OP's point is paragraph 11 in the "Camouflage" section.
--
python -c 'print "".join([chr(154 - ord(c)) for c in "U(17zX(%,5.z^5(17l8(%,5.Z*(93-965$l7+-"])'
Jul 18 '05 #11

[Steven]
If you have access to a syntax-aware editor, it will
help avoid such problems


Seconded. Here's my favourite real-world example of where the lack of
syntax colouring cost several man-days of work (though this couldn't
happen with modern C compilers):

extern void get_s(short* s);

void f()
{
int i; /* An integer to do something /*
short s; /* A short to do something */

get_s(&s);
/* Do something with s */
}

--
Richie Hindle
ri****@entrian.com

Jul 18 '05 #12
Here's another real world example, although it was in C:

char* ptr;
assert( ptr = malloc( memsize ); )

Of course, this worked when built in debug, but it took a while to
track down why it wasn't working in the release build (the assert()'s
were stripped out in the release builds, so ptr didn't allocate any
memory). Unfortunately, the runtime failure happened in an entirely
different part of the code, since ptr wasn't initialized to null, so
this particular routine just merrily stomped on whatever memory address
happened to initialize in ptr.

-- Paul

Jul 18 '05 #13
"Steve" <di****@yahoo.com> wrote in message
news:42**************@yahoo.com...
<snip>
What are some of other people's favourite tips for
avoiding bugs in the first place, as opposed to finding
them once you know they are there?

Fonts with slashed zeros and serifs.

-Tom

Jul 18 '05 #14
Paul McGuire wrote:
The code was filled with two key variables: t_1 and t_l. Printing out
the source in a Courier font made these two vars completely
indistinguishable,


Are you sure it was Courier? I'm looking at it now
in Courier, and they are different, although very
similar.

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 18 '05 #15

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

Similar topics

2
by: Patrik Carlsson | last post by:
I have a problem using Xerces with a template for a generic page-header getting a sub-tree as argument. The same stylesheet is working flawlessly in IE and Mozilla, though it would be nice to have...
0
by: Drake23 | last post by:
Hi, I need your help! I have to appoint the position of the current node in an nodelist. the nodelist I defined in a variable with: <xsl:variable name="CN"...
3
by: Beryl Small | last post by:
Hi, I have a third party software that needs to send information to an .aspx page for processing to communicate with an SQL database. The software sends the information something like this: ...
10
by: darrel | last post by:
I have this structure: mypage.aspx (class = mypage) myusercontro.ascx On the mypage.aspx I can declare a variable: animal = "monkey" I can read this from the UC by simply doing this:...
8
by: bryan | last post by:
Is there any way I can get the application path (the one returned by Request.ApplicationPath) in the Application_Start method in Global.asax? Request is not valid there. On a related note, is there...
1
by: Fred B | last post by:
I am launching a new thread from my application's main process (using VB.net 2003), and I can't get the child to receive the parameter I'm attempting to send it in a named data slot. The code...
1
by: simbarashe | last post by:
Hie could someone please help me with getting and using the current page url. I have a function that gets the url, I want to use it with header(location : XXX) but it wont work. The code is as...
6
by: sathyashrayan | last post by:
Dear Group, Please look at the following demo link. http://www.itsravi.com/demo/new_pms/admin/addproject.php
2
by: ismailc | last post by:
Hi, I don't know xml. The stylesheet identifies all the objects from DB & as it reads through the DB, it checks the next object "for-each", I need to check the third object as well & define within...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.