473,624 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2025
On 23 Dec 2006 14:38:19 -0800, Adam Atlas <ad**@atlas.stw rote:
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.stw rote:
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_nam es 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_In stance(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_bloc k(cls, name, bases, blockdict):
... return cls(name)
...
>># instances of your class with the appropriate names
class instance:
... __metaclass__ = C.from_class_bl ock
...
>>instance.na me
'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 "metaclasse s"
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_bloc k(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_bl ock
...
>>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
2067
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 question is: is there any way to make it work? Somebody proposed a patch for fileobject.c to allow stuff like fp = file(fp1.fileno()) but it looks like it's been rejected. I won't so bold as to request a change in Python. Should I try to re-write...
9
3171
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 WORDS_PER_LINE = 4; when counter == 7 is when the string Concatenation fails within the IF block.
6
1697
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. So here is what i do. I create a new node and insert it in a vecotr as follows: nodeCreator = new cNode(location, skew, offset,Beaconify,nodeId,directory); gNodeVector.push_back(*nodeCreator); //now lets delete the memory we created for the node
6
22509
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 instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
5
14792
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... /David
4
1654
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
1715
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: mypage.animal
20
6953
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 = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
6
3335
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..... Is there any java script to do this functionality...
0
8175
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8680
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8625
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8336
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
6111
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1487
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.