A class question

D

Donn Ingle

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:
( Without passing the name in like: x=X(name="x") )

Thx.
\d
 
B

Bruno Desthuilliers

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:

( 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()
 
C

Carl Banks

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:


( 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
 
H

Hrvoje Niksic

Donn Ingle said:
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, so
there is no single way to implement this sort of debugging. Instead,
print str(self), which will give you an idea of the identity of self,
or its contents.


Sbe unpx inyhr, urer vf n cbffvoyr vzcyrzragngvba:

vzcbeg vafcrpg

qrs _svaq(senzr, bow):
sbe anzr, inyhr va senzr.s_ybpnyf.vgrevgrzf():
vs inyhr vf bow:
erghea anzr
sbe anzr, inyhr va senzr.s_tybonyf.vgrevgrzf():
vs inyhr vf bow:
erghea anzr
envfr XrlReebe("Bowrpg abg sbhaq va senzr tybonyf be ybpnyf")

pynff K:
qrs qroht(frys):
cevag ("Pnyyre fgberf zr va %f (nzbat bgure cbffvoyr cynprf)"
% _svaq(vafcrpg.pheeragsenzr(1), frys))
Genpronpx (zbfg erprag pnyy ynfg):
Svyr "<fgqva>", yvar 1, va <zbqhyr>
Svyr "<fgqva>", yvar 4, va qroht
Svyr "<fgqva>", yvar 8, va _svaq
XrlReebe: 'Bowrpg abg sbhaq va senzr tybonyf be ybpnyf'
 
B

Bruno Desthuilliers

Hrvoje Niksic a écrit :
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.
 
H

Hrvoje Niksic

"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".
 
E

emorfo

was that on purpose?

martin

--http://noneisyours.marcher.namehttp://feeds.feedburner.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("Object not found in frame globals or locals")


class X:
def debug(self):
print ("Caller stores me in %s (among other possible places)"
% _find(inspect.currentframe(1), self))




Caller stores me in xyzzy (among other possible places)


Caller stores me in a (among other possible places)


Caller stores me in a (among other possible places)


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'
 
B

Bruno Desthuilliers

Hrvoje Niksic a écrit :
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 !-)
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.
 
H

Hrvoje Niksic

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.
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.
 
B

Bruno Desthuilliers

Hrvoje Niksic a écrit :
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.
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.
 
D

Donn Ingle

for humans:
Sweet. Thanks, I'll give it a go. It's only for debugging and will make life
easier.

\d
 
D

Donn Ingle

vzcbeg vafcrpg
qrs _svaq(senzr, bow):
sbe anzr, inyhr va senzr.s_ybpnyf.vgrevgrzf():
vs inyhr vf bow:
erghea anzr
sbe anzr, inyhr va senzr.s_tybonyf.vgrevgrzf():
vs inyhr vf bow:
erghea anzr
envfr XrlReebe("Bowrpg abg sbhaq va senzr tybonyf be ybpnyf")

pynff K:
qrs qroht(frys):
cevag ("Pnyyre fgberf zr va %f (nzbat bgure cbffvoyr cynprf)"
% _svaq(vafcrpg.pheeragsenzr(1), frys))

Now that's taking i18n too far. Klingon is not a widely understood
language :D


\d
 
H

Hrvoje Niksic

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.

While Java's variable declarations bear a superficial (syntactical)
similarity to C, their semantics is in fact equivalent to the
object-reference semantics we know in Python. They implicitly refer
to objects allocated on the heap and, just like in Python, the same
object can be referenced by multiple variables. If Java's model were
close to C/C++, that would not be possible without explicit
pointers/references since an object would be "contained" by the
variable.

Variables holding primitive types don't really influence the
variable/object relationship, since the values they hold are by nature
immutable and without identity.
 
D

Donn Ingle

While Java's variable declarations bear a superficial (syntactical)
similarity to C, their semantics is in fact equivalent to the
object-reference semantics we know in Python.

I come from Z80A/GWBASIC/VB and a little C, I would describe a Python
variable as a pointer - in that it contains the address of something.
What that "something" is, is a little fuzzy. Right now I imagine it's to a
kind of structure which has meta info about the object as well as it's
actual address.

How far off would that be?

\d
 
G

Gabriel Genellina

I come from Z80A/GWBASIC/VB and a little C, I would describe a Python
variable as a pointer - in that it contains the address of something.
What that "something" is, is a little fuzzy. Right now I imagine it's to
a
kind of structure which has meta info about the object as well as it's
actual address.

How far off would that be?

Almost true. A Python variable is a name inside a namespace, pointing to a
Python object. Many names may point to the same object, of course.
An object (in CPython) is a structure containing a reference count,
followed by a pointer to the object's type, followed by the object
contents itself. The object contents may as simple as a single value (e.g.
int or float objects) or rather complex (like the frame object which
contains about 18 other values, including many pointers to other
structures and arrays).
The object's type would be what you call the meta info, and contains the
type name, many pointers to functions (implementing the type methods) and
some flags describing the type behavior.
 
B

Bruno Desthuilliers

Hrvoje Niksic a écrit :
While Java's variable declarations bear a superficial (syntactical)
similarity to C, their semantics is in fact equivalent to the
object-reference semantics we know in Python. They implicitly refer
to objects allocated on the heap and, just like in Python, the same
object can be referenced by multiple variables.

You're talking about reference types here - not primitive types. And
even then, from what I remember (not having done any Java these last 4
years at least), Java's reference types are much closer to C++
references than to Python.
If Java's model were
close to C/C++, that would not be possible without explicit
pointers/references

The reference is implicit for non-primitive types.
since an object would be "contained" by the
variable.

Variables holding primitive types don't really influence the
variable/object relationship, since the values they hold are by nature
immutable and without identity.

Python's immutable types instances does have an identity, and follow the
same rules as mutable types instances - mutability set aside of course.
Which is not the case with Java, where primitive types and reference
types follow distinct rules. I'll check this out (not having done Java
for a couple years) and come back, but I certainly remember Java's model
as being way closer to C++ than to Python.
 
H

Hrvoje Niksic

You're talking about reference types here - not primitive types. And
even then, from what I remember (not having done any Java these last
4 years at least), Java's reference types are much closer to C++
references than to Python.

Feel free to look it up; I believe you will find the semantics of
assignment, parameter-passing, etc., exactly the same as in Python.
Python's immutable types instances does have an identity,

Just to clarify, here I was talking about Java's primitive-typed
variables, not drawing a parallel between Java and Python in that
area.
 
B

Bruno Desthuilliers

Hrvoje Niksic a écrit :
Bruno Desthuilliers <[email protected]>
writes:




Feel free to look it up; I believe you will find the semantics of
assignment, parameter-passing, etc., exactly the same as in Python.

I'll do - while perhaps not in a near future !-) - and keep you informed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top