Ask Your Question
0

How can I find out the name of some variable?

asked 2013-06-05 16:45:40 +0200

AndreWin gravatar image

updated 2014-11-10 16:29:06 +0200

tmonteil gravatar image

Hello! For example I have variable p in sage notebook. I need my class can find out the name of variable:

sage: p = 3
sage: my_class(p)
ans:  'p'

How to implement this feature? Thanks. P.S.: sorry if my english isn't good.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2013-06-05 17:45:05 +0200

tmonteil gravatar image

updated 2013-06-05 17:51:43 +0200

You should understand that an object may have different names:

sage: p = 3
sage: q = p
sage: id(p)
529391024
sage: id(q)
529391024

Here, p is the name of the same object than q (i mean, they both are the name of the same location in memory). Hence, your question is not well defined, since Sage (or Python) will not be able to make a difference between p and q. If you need such a feature, there may a better way to write your progam.

That said, you can try to look for your variable in the globals() dictionary:

sage: def my_name(p):
....:     for name, value in globals().items():
....:         if id(value) == id(p):
....:             return name

sage: my_name(p)
'p'
sage: my_name(q)
'p'

That said, this is quite a dirty method, and you should consider avoiding it.

edit flag offensive delete link more

Comments

Thank you very much!)))

AndreWin gravatar imageAndreWin ( 2013-06-06 07:40:50 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-06-05 16:45:40 +0200

Seen: 423 times

Last updated: Jun 05 '13