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

Getting the name of an assignment

Is it possible for an object, in its __init__ method, to find out if it
is being assigned to a variable, and if so, what that variable's name
is? I can think of some potentially ugly ways of finding out using
sys._getframe, but if possible I'd prefer something less exotic.
(Basically I have a class whose instances, upon being created, need a
'name' property, and if it's being assigned to a variable immediately,
that variable's name would be the best value of 'name'; to make the
code cleaner and less redundant, it would be best if it knew its own
name upon creation, just like functions and classes do, without the
code having to pass it its own name as a string.)

Dec 23 '06 #1
6 1995
On 23 Dec 2006 14:38:19 -0800, Adam Atlas <ad**@atlas.stwrote:
Is it possible for an object, in its __init__ method, to find out if it
is being assigned to a variable, and if so, what that variable's name
is? I can think of some potentially ugly ways of finding out using
sys._getframe, but if possible I'd prefer something less exotic.
(Basically I have a class whose instances, upon being created, need a
'name' property, and if it's being assigned to a variable immediately,
that variable's name would be the best value of 'name'; to make the
code cleaner and less redundant, it would be best if it knew its own
name upon creation, just like functions and classes do, without the
code having to pass it its own name as a string.)
I guess you mean something like this:
>>olle = Person()
olle.name
"olle"

Instead of:
>>olle = Person("olle")
olle.name
"olle"

It is not possible without ugly hacks. What you could use instead is
some kind of registry approach:

reg = {}
class Person:
def __init__(self, name):
self.name = name
reg[name] = self
>>Person("olle")
reg["olle"].name
"olle"

I think there are thousand different ways you could solve it.

--
mvh Björn
Dec 23 '06 #2
On Dec 23, 5:58 pm, "BJörn Lindqvist" <bjou...@gmail.comwrote:
On 23 Dec 2006 14:38:19 -0800, Adam Atlas <a...@atlas.stwrote:
Is it possible for an object, in its __init__ method, to find out if it
is being assigned to a variable, and if so, what that variable's name
is? I can think of some potentially ugly ways of finding out using
sys._getframe, but if possible I'd prefer something less exotic.
(Basically I have a class whose instances, upon being created, need a
'name' property, and if it's being assigned to a variable immediately,
that variable's name would be the best value of 'name'; to make the
code cleaner and less redundant, it would be best if it knew its own
name upon creation, just like functions and classes do, without the
code having to pass it its own name as a string.)I guess you mean something like this:
>olle = Person()
olle.name"olle"

Instead of:
>olle = Person("olle")
olle.name"olle"

It is not possible without ugly hacks. What you could use instead is
some kind of registry approach:

reg = {}
class Person:
def __init__(self, name):
self.name = name
reg[name] = self
>Person("olle")
reg["olle"].name"olle"

I think there are thousand different ways you could solve it.
Yeah, I've thought of ways like that. I was just hoping to make the
syntax as minimal and Pythonic as possible.

I have the following working:
import sys

class c:
def __init__(self):
f = sys._getframe(1)
names = [n for n in f.f_code.co_names if n not in f.f_locals]
if len(names) 0:
name = names[0]
print name

a = c() # prints 'a'
b = 'blah'
b = c() # prints nothing
Question: too evil?

Dec 24 '06 #3
On Sat, 23 Dec 2006 14:38:19 -0800, Adam Atlas wrote:
Is it possible for an object, in its __init__ method, to find out if it
is being assigned to a variable, and if so, what that variable's name
is?
What should the variable name be set to if you do one of the following?
john = eric = graham = terry = Named_Instance()

some_list = [None, 1, "string", Named_Instance()]

fred = Named_Instance(); barney = fred; del fred
Name assignment is not a one-to-one operation. An object can have no name,
one name or many names. If your code assumes such a one-to-one
relationship between names and objects, it is wrong.

I can think of some potentially ugly ways of finding out using
sys._getframe, but if possible I'd prefer something less exotic.
(Basically I have a class whose instances, upon being created, need a
'name' property, and if it's being assigned to a variable immediately,
that variable's name would be the best value of 'name'; to make the code
cleaner and less redundant, it would be best if it knew its own name
upon creation, just like functions and classes do, without the code
having to pass it its own name as a string.)
I suggest rethinking your data model, and accept that the name
attribute of an object is not necessarily the same as the name it is
bound to.

If you still want a convenience function that names the object and binds
it to a name at the same time, try something like this:

def Make_A_Named_Instance(name, *args, **kwargs):
globals()[name] = Named_Instance(*args, **kwargs)
globals()[name].name = name
You might be tempted to replace globals() with locals() in the above.
Don't -- it doesn't generally work:

http://docs.python.org/lib/built-in-funcs.html
--
Steven.

Dec 24 '06 #4
Adam Atlas wrote:
Is it possible for an object, in its __init__ method, to find out if it
is being assigned to a variable, and if so, what that variable's name
is? I can think of some potentially ugly ways of finding out using
sys._getframe, but if possible I'd prefer something less exotic.
(Basically I have a class whose instances, upon being created, need a
'name' property, and if it's being assigned to a variable immediately,
that variable's name would be the best value of 'name'; to make the
code cleaner and less redundant, it would be best if it knew its own
name upon creation, just like functions and classes do, without the
code having to pass it its own name as a string.)
As others have mentioned, in general the answer is no. However, class
statements do have access to the name they're assigned, so you could
abuse a class statement like this::
>># your class whose instances need a name property
class C(object):
... def __init__(self, name):
... self.name = name
... @classmethod
... def from_class_block(cls, name, bases, blockdict):
... return cls(name)
...
>># instances of your class with the appropriate names
class instance:
... __metaclass__ = C.from_class_block
...
>>instance.name
'instance'

Though it doesn't rely on private functions like sys._getframe, it's
still sure to confuse the hell out of your users. ;-)

STeVe
Dec 24 '06 #5
Thanks, Steven and Steven.

@Bethard:
Isn't it a bit convoluted to use metaclasses?
someinstance.__class__.__name__ does the same thing.

@D'Aprano:
Thanks for the advice to rethink my data model. I'm doing so right now,
and I've already come up with a way that makes more sense. :)

Dec 24 '06 #6
Adam Atlas wrote:
Isn't it a bit convoluted to use metaclasses?
Yep. It's a well known fact that putting "convoluted" and "metaclasses"
in the same sentence is repetitively redundant. ;-)
someinstance.__class__.__name__ does the same thing.
No, not really::
>>class C(object):
... def __init__(self, name):
... self.name = name
... @classmethod
... def from_class_block(cls, name, bases, blockdict):
... return cls(name)
...
>>c = C('foo')
c.name
'foo'
>>type(c)
<class '__main__.C'>
>>c.__class__.__name__
'C'
>>class foo:
... __metaclass__ = C.from_class_block
...
>>foo.name
'foo'
>>type(foo)
<class '__main__.C'>
>>foo.__class__.__name__
'C'

Note that the ``class foo`` statement is not creating a class. It's
creating an instance of ``C``. So it really is doing something pretty
different.

STeVe
Dec 24 '06 #7

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

Similar topics

4
by: Jan Burgy | last post by:
Hi all y'all, Consider the class down below. I've implemented it just because I needed the pushback method. Now of course the third line in __init__ doesn't work and I even understand why. My...
9
by: fudmore | last post by:
Hello Everybody. I have a Segmentation fault problem. The code section at the bottom keeps throwing a Segmentation fault when it enters the IF block for the second time. const int...
6
by: Affan Syed | last post by:
Hi, I am getting this weird problem. I know what i am doing is strange.. i am using C++ vectors and fopen, but for some reason if i used ofstream in the similar scenario it would give me errors....
6
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object...
5
by: David Rasmussen | last post by:
If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... ...
4
by: Mr. x | last post by:
Hello, I have declared in my program (*.aspx) something like this : <%@ Page Language="VB" Debug="true" %> .... <% dim current_view_page current_view_page = "1"
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:...
20
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt =...
6
by: Charleees | last post by:
Hi all, I have a DropDown and a TextBox just bekeow it... I have to get the selected value from dropdown and set it as textBox Text.. The thing is i have to do this Without PostBack..... ...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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
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
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
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,...

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.