473,799 Members | 3,212 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A class question

Hello,

Is there a way I can, for debugging, access the instance variable name from
within a class?
E.g:
Class X:
def debug(self):
print "My instance var is %s" % (some magic Python stuff)

So that:
>>>x = X()
x.debug()
My Instance var is x
( Without passing the name in like: x=X(name="x") )

Thx.
\d

Oct 29 '07 #1
16 1371
Donn Ingle a écrit :
Hello,

Is there a way I can, for debugging, access the instance variable name from
within a class?
E.g:
Class X:
def debug(self):
print "My instance var is %s" % (some magic Python stuff)

So that:
>>>x = X()
x.debug()
My Instance var is x

( Without passing the name in like: x=X(name="x") )
What should be the "variable name" in the following situations ?

a = b = c = X()
X().debug()
Oct 29 '07 #2
On Oct 28, 6:01 am, Donn Ingle <donn.in...@gma il.comwrote:
Hello,

Is there a way I can, for debugging, access the instance variable name from
within a class?
E.g:
Class X:
def debug(self):
print "My instance var is %s" % (some magic Python stuff)

So that:
>>x = X()
x.debug()
My Instance var is x

( Without passing the name in like: x=X(name="x") )

You could search the global and local namespaces of the caller for a
symbol that's bound to the same object as self. For instance, to find
a such a symbol in the caller's global namespace, this might work:

def debug(self):
for sym,value in sys._getframe(1 ).f_globals:
if value is self:
print "My instance var is %s" % sym

Improving the example left as an exercise. There's probably quite a
few recipes to do stuff like this in the Python Cookbook (quod
googla).

Also, note that some objects are not bound to any symbols but instead
are referenced by lists or other containers.
Carl Banks

Oct 29 '07 #3
Hrvoje Niksic a écrit :
Donn Ingle <do********@gma il.comwrites:
>Is there a way I can, for debugging, access the instance variable name from
within a class?
E.g:
Class X:
def debug(self):
print "My instance var is %s" % (some magic Python stuff)

As others have answered, an instance can live in many variables,
"be bound to many names" would be more accurate IMHO. Python's
"variables" are name=>object bindings.

Oct 29 '07 #4
2007/10/29, Hrvoje Niksic <hn*****@xemacs .org>:
Sbe unpx inyhr, urer vf n cbffvoyr vzcyrzragngvba:
...
was that on purpose?

martin

--
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
Oct 29 '07 #5
Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. com>
writes:
>As others have answered, an instance can live in many variables,

"be bound to many names" would be more accurate IMHO.
Technically more accurate maybe (but see below), but I was responding
to a beginner's post, so I was striving for ease of understanding.
Python's "variables" are name=>object bindings.
No reason to use quotes. Variable is just as acceptable a term, one
used by Python itself, as witnessed by the "vars" builtin, but also in
PEP 8, in the language reference, and elsewhere in the docs. Even the
quite technical language reference uses both terms, such as in this
paragraph under "Naming and binding":

If a name is bound in a block, it is a local variable of that
block. If a name is bound at the module level, it is a global
variable. (The variables of the module code block are local and
global.) If a variable is used in a code block but not defined
there, it is a free variable.

I disagree with the idea that the terms "name" and "binding" are the
only correct terminology. Python is not the first language to offer
pass-by-object-reference assignment semantics. It shares it with
Lisp, Java, and many others, none of which have problems with the term
"variable".
Oct 29 '07 #6
On Oct 29, 12:46 pm, "Martin Marcher" <mar...@marcher .namewrote:
2007/10/29, Hrvoje Niksic <hnik...@xemacs .org>:
Sbe unpx inyhr, urer vf n cbffvoyr vzcyrzragngvba:
...

was that on purpose?

martin

--http://noneisyours.mar cher.namehttp://feeds.feedburne r.com/NoneIsYours
for humans:
For hack value, here is a possible implementation:
import inspect
def _find(frame, obj):
for name, value in frame.f_locals. iteritems():
if value is obj:
return name
for name, value in frame.f_globals .iteritems():
if value is obj:
return name
raise KeyError("Objec t not found in frame globals or locals")
class X:
def debug(self):
print ("Caller stores me in %s (among other possible places)"
% _find(inspect.c urrentframe(1), self))
>>xyzzy = X()
xyzzy.debug ()

Caller stores me in xyzzy (among other possible places)
>>a = b = X()
a.debug()

Caller stores me in a (among other possible places)
>>b.debug()

Caller stores me in a (among other possible places)
>>X().debug()

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in debug
File "<stdin>", line 8, in _find
KeyError: 'Object not found in frame globals or locals'

Oct 29 '07 #7
Hrvoje Niksic a écrit :
Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. com>
writes:
>>As others have answered, an instance can live in many variables,
"be bound to many names" would be more accurate IMHO.

Technically more accurate maybe (but see below), but I was responding
to a beginner's post, so I was striving for ease of understanding.
The problem is that your formulation implies (to me at least) that the
variable is actually a kind of container for the object. And I'm not
sure being inaccurate really helps (OTHO, I often tend to get too
technical, so who knows which approach is the best here... At least, the
OP will now have both !-)
>Python's "variables" are name=>object bindings.

No reason to use quotes.
Yes, there's one : to mark the difference between Python-like
name=>object bindings and C-like labels-on-memory-address variables -
the latter model being the most commonly known to beginners.
Variable is just as acceptable a term,
Indeed - no need to refer to chapter and verse here, I've read the book
too !-)

(snip)
I disagree with the idea that the terms "name" and "binding" are the
only correct terminology.
Which is not what I meant here.

Oct 29 '07 #8
Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. com>
writes:
The problem is that your formulation implies (to me at least) that the
variable is actually a kind of container for the object.
I really didn't expect it to be read that way, especially since the
sentence claims that the same instance can reside in several
variables. If the term variable implied containment, that would not
be possible because different variables would imply different objects.

To be fair, the OP probably *did* confuse variables with containment,
and I rot13'ed my hack to avoid unnecessarily prolonging that
confusion. However, I don't think his confusion is a consequence of
inaccurate terminology, but of an inaccurate mental model of Python
objects. When the mental model is correct, the term "variable" works
as well as any other; when it's incorrect, using different words for
the same thing is of little help.
>>Python's "variables" are name=>object bindings.

No reason to use quotes.

Yes, there's one : to mark the difference between Python-like
name=>object bindings and C-like labels-on-memory-address variables
the latter model being the most commonly known to beginners.
Are you sure about the last part? It seems to me that in recent times
more Python beginners come from a Java background than from a C one.
In any case, "variable" is a sufficiently general concept not to be
tied to a specific implementation. That the concept of variable
differs among programming languages is for me not reason enough to
eschew it.
Oct 29 '07 #9
Hrvoje Niksic a écrit :
Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. com>
writes:
>The problem is that your formulation implies (to me at least) that the
variable is actually a kind of container for the object.

I really didn't expect it to be read that way, especially since the
sentence claims that the same instance can reside in several
variables. If the term variable implied containment, that would not
be possible because different variables would imply different objects.

To be fair, the OP probably *did* confuse variables with containment,
and I rot13'ed my hack to avoid unnecessarily prolonging that
confusion. However, I don't think his confusion is a consequence of
inaccurate terminology, but of an inaccurate mental model of Python
objects.
I'd think it has more to do with an inaccurate mental model of Python's
variables - hence my (perhaps useless) corrections.
When the mental model is correct, the term "variable" works
as well as any other; when it's incorrect, using different words for
the same thing is of little help.
This is where our POV differ. IMHO, wording and mental model have a
strong relationship - IOW, incorrect wording leads to incorrect
representation.
>>>Python's "variables" are name=>object bindings.
No reason to use quotes.
Yes, there's one : to mark the difference between Python-like
name=>object bindings and C-like labels-on-memory-address variables
the latter model being the most commonly known to beginners.

Are you sure about the last part?
Ok, I would not bet my hand on it !-) But the (non appliable) "pass by
value"/"pass by reference" question is still asked often enough here to
be an indication.
It seems to me that in recent times
more Python beginners come from a Java background than from a C one.
Java does have "container" variables for primitive types, and even for
"references ", Java's variables are more than names - they do hold type
informations too. Now I don't pretend to know how this is really
implemented, but AFAICT, and at least from a cognitive POV, Java's
variables model looks very close to the C/C++ model.

FWIW, I came to Python with a VB/C/Java/Pascal background, and Python
was the first language for which I needed to revise my mental model of
the "variable" concept.
In any case, "variable" is a sufficiently general concept not to be
tied to a specific implementation.
I'd say it's like the "type" concept : it's a general concept, but it's
not totally implementation-independant. "Type" doesn't mean exactly the
same thing in static or dynamic languages...
That the concept of variable
differs among programming languages is for me not reason enough to
eschew it.
I didn't mean to imply "variable" was an inappropriate term - just that
it may have a somewhat different meaning wrt/ some others more
mainstream languages. My humble experience is that rewording the whole
concept in terms of name=>object bindings did sometime help in the past.

Oct 29 '07 #10

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

Similar topics

8
2857
by: Bryan Parkoff | last post by:
I find an interesting issue that one base class has only one copy for each derived class. It looks like that one base class will be copied into three base classes while derived class from base class is executed. It means that three derived classes are pointed to a separated copy of base class. I do not allow second and third copy of base class to be created, but it must remain only first copy of base class. It allows three derived...
20
2894
by: modemer | last post by:
Question is as in subject. For example: class BaseClass { public: void func() { do something; } // I don't want this function being overloaded in its inherited class };
1
2274
by: Alfonso Morra | last post by:
if I have a class template declared as ff: (BTW is this a partial specialization? - I think it is) template <typename T1, myenum_1 e1=OK, my_enum_2=NONE> class A { public: A(); virtual ~A() ;
21
4083
by: Jon Slaughter | last post by:
I have a class that is basicaly duplicated throughout several files with only members names changing according to the class name yet with virtually the exact same coding going on. e.g. class A { std::vector<B*> Bs; public:
0
1437
by: Sebastian Hiller | last post by:
Hello, i'm new to .Net (i'm using VB as language and i'm working in the code-behind mode) and i can't solve the following problem: I have a WebForm and want to Add a UserControl (classname:QuestionControl) as many times as there are rows in a DataTable (also named Questions) in a DataSet. But this UserControl is ,for reasons of structuring, not a member of the WebForm Object in which it should be displayed, it is member of another class...
6
2121
by: rodchar | last post by:
Hey all, I'm trying to understand Master/Detail concepts in VB.NET. If I do a data adapter fill for both customer and orders from Northwind where should that dataset live? What client is responsible for instantiating the orders class? Would it be the ui layer or the master class in the business layer? thanks,
2
1609
by: Chris Puncher | last post by:
Hi. I have a RCW class that was generated by the VS.NET2003 IDE when I added a COM dll reference to my project. This all works fine when I call methods on it. My initial problem is that in ASP.NET I would like to add this to the Session object whilst using SQLServer as the session storage. Unfortunately, as this required the RCW class to be serializable, this won't work, and throws an exception saying you can't Serialize the Session...
9
1656
by: needin4mation | last post by:
I have a .aspx file and it's src. I also have a third file, a class that the src references. Everything is in the same directory/folder. Everything has the same namespace. How do I reference the class in my c# .src file? I don't believe this is an ASP.NET question, but a OOP C# question, thus my post here. I have searched and I thought it was with: using FilterSQL; //the name of my class using reports.FilterSQL; //name of...
43
2099
by: Tony | last post by:
I'm working with GUI messaging and note that MFC encapsulates the message loop inside of a C++ class member function. Is this somehow inherently less robust than calling the message loop functions within main? (It just doesn't "feel" right to me). Example 1: class MyProg { public:
2
1510
by: K Viltersten | last post by:
Suppose there is the following class structure. class S {...} class A : S {...} class B : S {...} class A1 : A {void m(){...}} class B1 : B {void m(){...}} class B2 : B {...} Just to clarify the issue. A1 and B1 share a method (void m() ) AND B2 doesn't have that
0
9541
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
10485
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
10252
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
10231
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,...
0
10027
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9073
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.