Re: Descriptor: class name precedence over instance name

2016-07-03 Thread Veek. M
Ian Kelly wrote:

> On Sat, Jul 2, 2016 at 3:34 AM, Veek. M  wrote:
>> So essentially from what Ian said:
>> data_descriptor_in_instance -> instance_attribute -> non-
>> data_descriptor_in_instance -->__mro__
>>
>> is how the search takes place. Correct?
> 
> Close, but I would write it as:
> data_descriptor_in_class_including_mro -> instance_attribute ->
> non_data_descriptor_or_class_attribute_including_mro
> 
> In either case the class dict search is in __mro__ order. You can find
> the actual implementation here:
> 
> https://hg.python.org/cpython/file/30099abdb3a4/Objects/object.c#l1326
> 
> Roughly, the algorithm is this:
> 
> tp = type(obj)
> 
> # This call searches the MRO.
> descr = _PyType_Lookup(tp, name)
> 
> if descr != NULL and is_data_descriptor(descr):
> return descr.__get__(obj, tp)
> 
> if name in obj.__dict__:
> return obj.__dict__[name]
> 
> if descr != NULL and is_non_data_descriptor(descr):
> return descr.__get__(obj, tp)
> 
> if descr != NULL:
> return descr
> 
> raise AttributeError(name)
> 
>> --
>>
>> Regarding part2 of the Q, :) Ian hasn't explained it, so I'm not sure
>> how to explain it better :) but i'll try given that he has clarified
>> part of the answer.
>>
>> Basically Beazley has a TypedProperty descriptor class, and in class
>> Foo he instantiates:
>>  name = TypedProperty
>> Then he does f = Foo()
>>
>> Thanks to Ian, we now know that any lookup on 'f' eg: f.name would
> 
> Not *any* lookup, only one for which there is a declared descriptor.
> So in this example f.name or f.num would resolve according to the
> descriptor's __get__ method, but any other attribute lookup would just
> return whatever value is set on the instance (if any).
> 
>> cause.. well.. the f.name(TypedProperty-descriptor) to gain
>> precedence thus hiding the f.name attribute! Therefore he needs to
>> name-decorate or in this example append an '_' for whatever stupid
>> reason.
> 
> Right, if the "name" descriptor tried to store the value in the
> unmangled "name" instance attribute, then its getattr call would just
> recur back to the descriptor and you'd have an infinite loop.
> 
> In my opinion the mangling should be a bit heavier than what's done in
> this example, to avoid collisions between the descriptor and the class
> that's using it. I like to follow the pattern of __foo name mangling,
> so I would have instead used:
> 
> self.name = "_TypedProperty__" + name

Ouch - that's above my skill level (Python types, especially 
PyType_Lookup has no docs but i did find 
https://docs.python.org/3/c-api/index.html) and I got side tracked into reading 
the PCIe spec so 
today went down the drain. I'm putting this on hold as totally not 
understood and requiring much more reading. I'll drag it up later if 
everyones okay with it.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Descriptor: class name precedence over instance name

2016-07-02 Thread Ian Kelly
On Sat, Jul 2, 2016 at 3:34 AM, Veek. M  wrote:
> So essentially from what Ian said:
> data_descriptor_in_instance -> instance_attribute -> non-
> data_descriptor_in_instance -->__mro__
>
> is how the search takes place. Correct?

Close, but I would write it as:
data_descriptor_in_class_including_mro -> instance_attribute ->
non_data_descriptor_or_class_attribute_including_mro

In either case the class dict search is in __mro__ order. You can find
the actual implementation here:

https://hg.python.org/cpython/file/30099abdb3a4/Objects/object.c#l1326

Roughly, the algorithm is this:

tp = type(obj)

# This call searches the MRO.
descr = _PyType_Lookup(tp, name)

if descr != NULL and is_data_descriptor(descr):
return descr.__get__(obj, tp)

if name in obj.__dict__:
return obj.__dict__[name]

if descr != NULL and is_non_data_descriptor(descr):
return descr.__get__(obj, tp)

if descr != NULL:
return descr

raise AttributeError(name)

> --
>
> Regarding part2 of the Q, :) Ian hasn't explained it, so I'm not sure
> how to explain it better :) but i'll try given that he has clarified
> part of the answer.
>
> Basically Beazley has a TypedProperty descriptor class, and in class Foo
> he instantiates:
>  name = TypedProperty
> Then he does f = Foo()
>
> Thanks to Ian, we now know that any lookup on 'f' eg: f.name would

Not *any* lookup, only one for which there is a declared descriptor.
So in this example f.name or f.num would resolve according to the
descriptor's __get__ method, but any other attribute lookup would just
return whatever value is set on the instance (if any).

> cause.. well.. the f.name(TypedProperty-descriptor) to gain precedence
> thus hiding the f.name attribute! Therefore he needs to name-decorate or
> in this example append an '_' for whatever stupid reason.

Right, if the "name" descriptor tried to store the value in the
unmangled "name" instance attribute, then its getattr call would just
recur back to the descriptor and you'd have an infinite loop.

In my opinion the mangling should be a bit heavier than what's done in
this example, to avoid collisions between the descriptor and the class
that's using it. I like to follow the pattern of __foo name mangling,
so I would have instead used:

self.name = "_TypedProperty__" + name
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Descriptor: class name precedence over instance name

2016-07-02 Thread Veek. M
Ben Finney wrote:

> "Veek. M" <vek.m1...@gmail.com> writes:
> 
>> Trying to make sense of this para:
> 
> At the risk of being ruse, I am trying to make sense of some
> paragraphs in the messages you write here. Could you take a little
> more time to write clearly, as a way of communicating in this forum?
> 
>> Is he say that Descriptors are a special case where Foo is checked
>> first, then what - Base classes..? or does he hop back to look in the
>> instance? How is C3 Linearization altered?
> 
> I really have no idea what this paragraph means. Can you please write
> again assuming we don't know already what you are trying to say?
> 

Sorry about that, I found it hard to read too (when I came back to it). 

I was trying to figure out the order in which attributes are looked up. 
Beazley's a great book, but sometimes he kills me and mounts my head on 
a pike - page 127 - Descriptors section, last para.

He says that descriptor-attribute-names in a class, take precedence in a 
attribute lookup wrt instance attributes.

When you do an x.a, python goes on a hunt for 'a' - the whole binding 
idea; typically, that is, Instance Name Space -> Class NS -> BaseClasses
(C3 Linearization algorithm)

Therefore, I was wondering how he could start the search at the 
instance-Class, instead of the instance. When you print __mro__ you get 
a list of classes that are traversed but there's no explicit mention 
within the __mro__ that the instance is searched first. So I wanted to 
know if there was any implications to C3/__mro__

So essentially from what Ian said:
data_descriptor_in_instance -> instance_attribute -> non-
data_descriptor_in_instance -->__mro__

is how the search takes place. Correct?
--

Regarding part2 of the Q, :) Ian hasn't explained it, so I'm not sure 
how to explain it better :) but i'll try given that he has clarified 
part of the answer.

Basically Beazley has a TypedProperty descriptor class, and in class Foo
he instantiates:
 name = TypedProperty
Then he does f = Foo()

Thanks to Ian, we now know that any lookup on 'f' eg: f.name would 
cause.. well.. the f.name(TypedProperty-descriptor) to gain precedence 
thus hiding the f.name attribute! Therefore he needs to name-decorate or 
in this example append an '_' for whatever stupid reason.

I think i've got the jist down pat so :p
Here's the image:
http://storage1.static.itmages.com/i/16/0702/h_1467451175_7972040_b5037f6b46.png

(thanks Ian)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Descriptor: class name precedence over instance name

2016-07-01 Thread Ben Finney
"Veek. M"  writes:

> Trying to make sense of this para:

At the risk of being ruse, I am trying to make sense of some paragraphs
in the messages you write here. Could you take a little more time to
write clearly, as a way of communicating in this forum?

> Is he say that Descriptors are a special case where Foo is checked 
> first, then what - Base classes..? or does he hop back to look in the 
> instance? How is C3 Linearization altered?

I really have no idea what this paragraph means. Can you please write
again assuming we don't know already what you are trying to say?

-- 
 \  “[I]t is impossible for anyone to begin to learn that which he |
  `\thinks he already knows.” —Epictetus, _Discourses_ |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Descriptor: class name precedence over instance name

2016-07-01 Thread Ian Kelly
On Fri, Jul 1, 2016 at 10:27 PM, Veek. M  wrote:
> Trying to make sense of this para:
>
> --
> Also, the attribute name used by the class to hold a descriptor takes
> prece- dence over attributes stored on instances.
>
> In the previous example,
> this is why the descriptor object takes a name parameter and why the
> name is changed slightly by inserting a leading underscore. In order
> for the descriptor to store a value on the instance, it has to pick a
> name that is different than that being used by the descriptor itself
> -
> Under normal circumstances, when I do an attribute lookup:
> x = Foo()
> x.a
> he will first check 'x' then Foo.
>
> Is he say that Descriptors are a special case where Foo is checked
> first,

It depends whether it's a "data descriptor" or not. A data descriptor
is one that defines at least one of __set__ or __delete__, not just
__get__. Data descriptors take precendence over instance attributes.
Instance attributes take precedence over non-data descriptors.

> then what - Base classes..?

Checking base classes is part of checking the class. If a base class
has a data descriptor, that will likewise take precedence over the
instance attribute, which will likewise take precedence over non-data
descriptors in the base class.

> or does he hop back to look in the
> instance? How is C3 Linearization altered?

It's not.

> Additionally,
> class Foo:
>def __init__(self, name, value):
>  self.name = name
>
> cannot be done because
> x = Foo('bar', 10)
>
> x.bar will..? attribute in class takes precedence.. great, isn't that
> what we want?

I don't understand what you're asking here or what this example has to
do with descriptors.
-- 
https://mail.python.org/mailman/listinfo/python-list


Descriptor: class name precedence over instance name

2016-07-01 Thread Veek. M
Trying to make sense of this para:

--
Also, the attribute name used by the class to hold a descriptor takes
prece- dence over attributes stored on instances. 

In the previous example,
this is why the descriptor object takes a name parameter and why the
name is changed slightly by inserting a leading underscore. In order
for the descriptor to store a value on the instance, it has to pick a
name that is different than that being used by the descriptor itself
-
Under normal circumstances, when I do an attribute lookup:
x = Foo()
x.a
he will first check 'x' then Foo.

Is he say that Descriptors are a special case where Foo is checked 
first, then what - Base classes..? or does he hop back to look in the 
instance? How is C3 Linearization altered?


Additionally,
class Foo:
   def __init__(self, name, value):
 self.name = name

cannot be done because
x = Foo('bar', 10)

x.bar will..? attribute in class takes precedence.. great, isn't that 
what we want?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to get a class instance name during creation?

2008-10-04 Thread Aaron Castironpi Brady
On Oct 3, 1:46 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 dmitrey a écrit :

  hi all,
  I have a code
  z = MyClass(some_args)
  can I somehow get info in MyClass __init__ function that user uses z
  as name of the variable?

  I.e. to have __init__ function that creates field z.name with value
  z.

 This has been debated to hell and back. To make a long story short, here
 are two common use cases:

 x = MyClass()
 y = x
 del x

 objects = [MyClass() for i in range(100)]

 If you can come with a meaningfull answer to what's *the* name of any
 of the MyClass instance(s) in both cases, then please let us know...

Hmmm, just thinking:

What about a function:

autoname( 'x= MyClass' )

which calls exec as well as determines the name?  That could use
'code' and 'ast' modules and 'parse', or just take the first \w
characters, assuming assignment, or:

autoname( 'x', MyClass() )

which executes assignment and sets an attr or calls a method on the
second arg.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a class instance name during creation?

2008-10-04 Thread dmitrey
On Oct 3, 9:46 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 dmitrey a écrit :

  hi all,
  I have a code
  z = MyClass(some_args)
  can I somehow get info in MyClass __init__ function that user uses z
  as name of the variable?

  I.e. to have __init__ function that creates field z.name with value
  z.

 This has been debated to hell and back. To make a long story short, here
 are two common use cases:

 x = MyClass()
 y = x
 del x

 objects = [MyClass() for i in range(100)]

 If you can come with a meaningfull answer to what's *the* name of any
 of the MyClass instance(s) in both cases, then please let us know...

I had seen the examples during google search, still I hoped for an
answer to my exact situation. I know for sure there will be no
renaming and creating like the above objects = [MyClass() for i in
range(100)].
as for the z = MyClass(some, args, 'z') I had it in my mind but I
hoped to have something automatic, w/o the arg 'z'.
Regards, D.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a class instance name during creation?

2008-10-04 Thread Ben Finney
dmitrey [EMAIL PROTECTED] writes:

 On Oct 3, 9:46 pm, Bruno Desthuilliers
 [EMAIL PROTECTED] wrote:
  x = MyClass()
  y = x
  del x
 
  objects = [MyClass() for i in range(100)]
 
  If you can come with a meaningfull answer to what's *the* name of
  any of the MyClass instance(s) in both cases, then please let us
  know...
 
 I had seen the examples during google search, still I hoped for an
 answer to my exact situation. I know for sure there will be no
 renaming and creating like the above objects = [MyClass() for i in
 range(100)].

You *know* this, *for sure*? The only way I can think of that would
give you such certain knowledge that such a situation will not happen
is an automated, full-coverage unit test suite of all code that uses
your class. Which is an excellent position to be in, so I commend you
on your diligence.

So, why is it that you wish to restrict users of your class to never
do such normal operations with instances as in the above examples?
What problem are you solving by this restriction?

-- 
 \   “Holy human pressure cookers, Batman!” —Robin |
  `\   |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


how to get a class instance name during creation?

2008-10-03 Thread dmitrey
hi all,
I have a code
z = MyClass(some_args)
can I somehow get info in MyClass __init__ function that user uses z
as name of the variable?

I.e. to have __init__ function that creates field z.name with value
z.

Thank you in advance, D.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a class instance name during creation?

2008-10-03 Thread Gabriel Genellina
En Fri, 03 Oct 2008 15:04:01 -0300, dmitrey [EMAIL PROTECTED]  
escribió:



I have a code
z = MyClass(some_args)
can I somehow get info in MyClass __init__ function that user uses z
as name of the variable?

I.e. to have __init__ function that creates field z.name with value
z.


No. I'd just write it as:

z = MyClass(some, args, 'z')

wich is pretty simple and readable (although you have to repeat the 'z').  
All the alternative ways I know of require too much black magic.


--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a class instance name during creation?

2008-10-03 Thread Bruno Desthuilliers

dmitrey a écrit :

hi all,
I have a code
z = MyClass(some_args)
can I somehow get info in MyClass __init__ function that user uses z
as name of the variable?

I.e. to have __init__ function that creates field z.name with value
z.


This has been debated to hell and back. To make a long story short, here 
are two common use cases:


x = MyClass()
y = x
del x

objects = [MyClass() for i in range(100)]

If you can come with a meaningfull answer to what's *the* name of any 
of the MyClass instance(s) in both cases, then please let us know...

--
http://mail.python.org/mailman/listinfo/python-list


Re: Get the instance name from a list by Reflection

2007-10-22 Thread Gabriel Genellina

--- sccs cscs [EMAIL PROTECTED] escribió:

 Thank you, but i believe that i could get all
 variables names that reference an instance: i need
 it for a special debug tool... It seems that
 knowledge exists somewhere into the Python
 interpreter...

Please read first the FAQ item posted previously, and this article:
http://effbot.org/zone/python-objects.htm
Then it should be clear that any object may be referenced by one name,
many names, or no name at all. By example:

py a = [1, 2, 3]
py b = four
py a.append(b)
py a
[1, 2, 3, 'four']
py b = 5
py c = b
py id(b)
10049608
py id(c)
10049608
py b is c
True

In this case there is only one name referencing the list (a), two
names referencing the number 5 (b and c), and no name referencing the
string four, altough it was earlier known as b.
Python is built around namespaces: mappings FROM names TO objects. A
name refers to a single object, but the inverse is not true. You can
invert the relation examining possible namespaces and seeing if the
object is referenced, and by which names. Something like this:

py def invert(obj, namespace):
...   result = []
...   for key,value in namespace.iteritems():
... if value is obj:
...   result.append(key)
...   return result
...
py invert(a, globals())
['a']
py invert(5, globals())
['c', 'b']
py invert(123, globals())
[]
py invert([1, 2, 3, 'four'], globals())
[]

You can pass globals(), locals(), vars(some_object) as the namespace
argument.

--
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Get the instance name from a list by Reflection

2007-10-22 Thread Larry Bates
Jean-Paul Calderone wrote:
 On Sat, 20 Oct 2007 21:10:34 +0200 (CEST), sccs cscs [EMAIL PROTECTED] 
 wrote:
 Hello,
 I cannot find into documentation how to get the instance name. I found 
 the attributes __dict__,__class__ ,__bases__ __name__ ,
 but if i have the code:

 class A :pass
 a1 = A ()
 a2 = A ()
 aList = [a1,a2]
 for elem in aList :
print elem.__instance_name__ ???

 I expect to have a1 a2 ...
 But it does not work ...
 help please
 Zorgi
 
$ python
Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
 class A: pass
...
 a1 = A()
 a2 = A()
 aList = [a1, a2]
 import __main__
 from twisted.python.reflect import objgrep, isSame
 for elem in aList:
... objgrep(__main__, elem, isSame)
...
['.aList[0]', '.elem', '.a1']
['.aList[1]', '.elem', '.a2']

 
 Don't see how this could help,
 
 Jean-Paul
If you want to accomplish something like this use the following:

class A(object):
 def __init__(self, name=None):
 self.name=name

aList=[]
aList.append(A(name='a1')
aList.append(A(name='a2')
for elem in aList:
 print elem.name

-Larry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the instance name from a list by Reflection

2007-10-22 Thread jon vspython
May be, you could check against globals() dictionary looking for matching
id()'s:

def find_name(identifier):
 for k,v in globals().items():
 if id(v) == id(identifier):
 return k
-- 
http://mail.python.org/mailman/listinfo/python-list

Get the instance name from a list by Reflection

2007-10-20 Thread sccs cscs
Hello,
I cannot find into documentation how to get the instance name. I found the 
attributes __dict__,__class__ ,__bases__ __name__ ,
but if i have the code:

class A :pass
a1 = A ()
a2 = A ()
aList = [a1,a2]
for elem in aList :
print elem.__instance_name__ ???

I expect to have a1 a2 ...
But it does not work ...
help please
Zorgi

 
-
 Ne gardez plus qu'une seule adresse mail ! Copiez vos mails vers Yahoo! Mail -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Get the instance name from a list by Reflection

2007-10-20 Thread Jean-Paul Calderone
On Sat, 20 Oct 2007 21:10:34 +0200 (CEST), sccs cscs [EMAIL PROTECTED] wrote:
Hello,
I cannot find into documentation how to get the instance name. I found the 
attributes __dict__,__class__ ,__bases__ __name__ ,
but if i have the code:

class A :pass
a1 = A ()
a2 = A ()
aList = [a1,a2]
for elem in aList :
print elem.__instance_name__ ???

I expect to have a1 a2 ...
But it does not work ...
help please
Zorgi

$ python
Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
[GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
Type help, copyright, credits or license for more information.
 class A: pass
...
 a1 = A()
 a2 = A()
 aList = [a1, a2]
 import __main__
 from twisted.python.reflect import objgrep, isSame
 for elem in aList:
... objgrep(__main__, elem, isSame)
...
['.aList[0]', '.elem', '.a1']
['.aList[1]', '.elem', '.a2']


Don't see how this could help,

Jean-Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the instance name from a list by Reflection

2007-10-20 Thread Carsten Haese
On Sat, 2007-10-20 at 21:10 +0200, sccs cscs wrote:
 Hello,
 I cannot find into documentation how to get the instance name.

That's because this is, in general, impossible. An object can have any
number of names, even zero names, and an object doesn't know which names
it has.

Why do you think you need to find out an object's name?

-- 
Carsten Haese
http://informixdb.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get the instance name from a list by Reflection

2007-10-20 Thread Gabriel Genellina
En Sat, 20 Oct 2007 16:10:34 -0300, sccs cscs [EMAIL PROTECTED] escribi�:

 I cannot find into documentation how to get the instance name. I found  
 the attributes __dict__,__class__ ,__bases__ __name__ ,
 but if i have the code:

In general, you can't. There is no such thing as the instance name.
See  
http://www.python.org/doc/faq/programming/#how-can-my-code-discover-the-name-of-an-object

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list

Introspection Class/Instance Name

2006-04-26 Thread *binarystar*
Hello there,

what method would you use to return the name of the class and/or 
instance introspectively eg.

class Bollocks:

def __init__( self ):

print self.__method_that_returns_class_name__()
print self.__method_that_returns_instance_name__()


instance_of_bollocks= Bollocks()

# Which outputs

'Bollocks'
'instance_of_bollocks'



I have been scouring the 2.4 docs ... I am sure it is frustratingly simple

thx in advance

**
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Introspection Class/Instance Name

2006-04-26 Thread Roland Heiber
*binarystar* wrote:
 Hello there,
 
 what method would you use to return the name of the class and/or 
 instance introspectively eg.
 
 class Bollocks:
 
 def __init__( self ):

 print self.__method_that_returns_class_name__()
 print self.__method_that_returns_instance_name__()
 
 
 instance_of_bollocks= Bollocks()
 
 # Which outputs
 
 'Bollocks'
 'instance_of_bollocks'
 
 
 
 I have been scouring the 2.4 docs ... I am sure it is frustratingly simple
 
 thx in advance
 
 **

Hi,

take a look at self.__class__.__name__ for the Class-name.

HtH, Roland
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Introspection Class/Instance Name

2006-04-26 Thread [EMAIL PROTECTED]
What about:

py class A:
py. def __init__(self):
py. print self.__class__.__name__
py. print str(self)
py. def __str__(self):
py. return 'instance of %s' % self.__class__.__name__
py. 
py a = A()
A
instance of A
py

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Introspection Class/Instance Name

2006-04-26 Thread Duncan Booth
*binarystar* wrote:

 class Bollocks:
  
  def __init__( self ):
   
   print self.__method_that_returns_class_name__()
   print self.__method_that_returns_instance_name__()
 
 
 instance_of_bollocks = Bollocks()
 
 # Which outputs
 
 'Bollocks'
 'instance_of_bollocks'
 

 class Bollocks(object):
def name_of_instance(self):
return self


 instance_of_bollocks = Bollocks()
 print instance_of_bollocks.__class__.__name__
Bollocks
 print instance_of_bollocks.name_of_instance()
self
 

At the time when the method is called, 'self' is a perfectly valid name for 
the instance. Seriously though, how do you expect a method to decide if you 
do:

 another_name = instance_of_bollocks
 print another_name.name_of_instance()
??? which name should appear here ???
 more = [another_name]*5
 print more[2]
??? and what name here ???

and did you want a global name, or a local variable from some function and 
if so which function and at which stack level?

Python does actually give you sufficient introspection to do this, but you 
have to write some fairly complex code to iterate through the namespaces 
you are interested in searching for the object.

A much more reasonable solution is to give your object a name attribute:

 class Bollocks(object):
def __init__(self, name):
self.name = name


 instance_of_bollocks = Bollocks('Archimedes')
 print instance_of_bollocks.name
Archimedes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Introspection Class/Instance Name

2006-04-26 Thread robert
*binarystar* wrote:
 Hello there,
 
 what method would you use to return the name of the class and/or 
 instance introspectively eg.
 
 class Bollocks:
 
 def __init__( self ):

 print self.__method_that_returns_class_name__()
 print self.__method_that_returns_instance_name__()
 
 
 instance_of_bollocks= Bollocks()
 
 # Which outputs
 
 'Bollocks'
 'instance_of_bollocks'
 

self.__class__ is good for getting instance's top class

yet Python is weak on introspecting the namespace of its definitions - 
funcs and classes. it stops at sys._getframe().f_code.co_name

thus, e.g. for things like super() you need always to re-type the class 
name where you just write in!?

maybe Py3K brings more ? Maybe There could be compiler-variables like
__CLASS__ ,  __FUNC__ for things like super(), recursion etc.
(compare http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491265 )

-robert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-05 Thread max(01)*
many many thanks to each and everyone who bothered to answer my op.
best regards
macs
--
http://mail.python.org/mailman/listinfo/python-list


instance name

2005-04-02 Thread max(01)*
hi.
is there a way to define a class method which prints the instance name?
e.g.:
 class class_1:
...   def myName(self):
... what should i do here
...
 instance_1 = class_1()
 instance_1.myName()
'instance_1'

bye
macs
--
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-02 Thread Andrew Koenig
max(01)* [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 is there a way to define a class method which prints the instance name?

The term the instance name is misleading, because it assumes, without 
saying so explicitly, that every instance has a unique name.

In fact, there is no reason that an instance needs to have a name at all, or 
that it should have only one.

You gave this example:

instance_1 = class_1()
instance_1.myName()

but what if I did this instead?

class_1().myName()

Or this?

instance_1 = class_1()
instance_2 = instance_1
instance_2.myName()


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-02 Thread Irmen de Jong
max(01)* wrote:
 hi.
 
 is there a way to define a class method which prints the instance name?
 
 e.g.:
 
 class class_1:
 ...   def myName(self):
 ... what should i do here
 ...
 instance_1 = class_1()
 instance_1.myName()
 'instance_1'

 
 bye
 
 macs

What should the following do, you think?

 a=class_1()
 b=a
 b is a
True
 b.myName()
print what

There is no such thing as the instance name.
(a and b both point to the same instance, in my example)

Also: why do you want this? It smells like you're
actually looking for the use of a dict to do your job.

--Irmen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-02 Thread max(01)*
Andrew Koenig wrote:
max(01)* [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]


is there a way to define a class method which prints the instance name?

The term the instance name is misleading, because it assumes, without 
saying so explicitly, that every instance has a unique name.

In fact, there is no reason that an instance needs to have a name at all, or 
that it should have only one.

You gave this example:
instance_1 = class_1()
instance_1.myName()
but what if I did this instead?
class_1().myName()
Or this?
instance_1 = class_1()
instance_2 = instance_1
instance_2.myName()

excellent points.
i'll get back with proper questions afterwards.
thanks
macs
--
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-02 Thread max(01)*
Irmen de Jong wrote:
max(01)* wrote:
hi.
is there a way to define a class method which prints the instance name?
e.g.:

class class_1:
...   def myName(self):
... what should i do here
...
instance_1 = class_1()
instance_1.myName()
'instance_1'
bye
macs

What should the following do, you think?

a=class_1()
b=a
b is a
True
b.myName()
print what
There is no such thing as the instance name.
(a and b both point to the same instance, in my example)
Also: why do you want this? It smells like you're
actually looking for the use of a dict to do your job.
right. it seems i need to dive deeper in the language spirit.
thanks a lot
bye
macs
--
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-02 Thread Mark Winrock
max(01)* wrote:
hi.
is there a way to define a class method which prints the instance name?
e.g.:
  class class_1:
...   def myName(self):
... what should i do here
...
  instance_1 = class_1()
  instance_1.myName()
'instance_1'
 
bye
macs
macs,
The object instance doesn't know about the identifier to which you 
assigned it (but see my example below using the inspect module).

If you are just trying to identify different instances, you can get a 
unique instance identifier from hash() function
	hash(instance1)

or
self.__hash__(), or hash(self) from within the object
The default __str__ for a class will normally return something similar 
with more information , so that when you
	print instance_1
you get a string in the following format:
	module.classname object at hashvalue

The following is a very, very, very weak example of how you might use 
inspect to get the information you want. This is not a robust example at 
all, and I imagine it could have many ways it will fail. The init uses 
inspect information to dip into the source file and parse out the info 
-- like I said, this is not a robust parse.
# 
import os,sys

class class_1(object):
def __init__(self):
import inspect
self.lineno = inspect.currentframe().f_back.f_lineno
self.filename = inspect.currentframe().f_back.f_code.co_filename
self.initial_instance = None
try:
# i'm not sure if filename is full path or not at this time
f=open(self.filename,'r')
lines=f.readlines()
s = lines[self.lineno-1]
split = s.split()
try:
# find the assignment if possible
i = split.index('=')
self.initial_instance = split[i-1]
except ValueError:
pass
finally:
f.close()
def myName(self):
print 'my initial instance was \'%s\''%(self.initial_instance)
if __name__ == '__main__':
# two straight up examples
instance_1 = class_1()
instance_2 = class_1()
instance_1.myName()
instance_2.myName()
#
class_1().myName()
c = instance_1
c.myName()
# ---
I got the following results:
my initial instance was 'instance_1'
my initial instance was 'instance_2'
my initial instance was 'None'
my initial instance was 'instance_1'

Best-regards,
Mark
--
http://mail.python.org/mailman/listinfo/python-list


Re: instance name

2005-04-02 Thread Bengt Richter
On Sat, 02 Apr 2005 15:48:21 GMT, max(01)* [EMAIL PROTECTED] wrote:

hi.

is there a way to define a class method which prints the instance name?

e.g.:

  class class_1:
...   def myName(self):
... what should i do here
...
  instance_1 = class_1()
  instance_1.myName()
'instance_1'
 

Names in any given name space do not have a 1:1 relationship with class 
instances.
If you want to give an instance its own name, give it a name when you create it,
or attach a name to the instance. E.g, maybe this will give you an idea:

  class Ego(object):
 ... def __init__(self, name='(anonymous)'): self.name = name
 ... def myName(self): return self.name
 ...
  instance_1 = Ego('one')
  instance_2 = Ego('two')
  instance_1.myName()
 'one'
  instance_2.myName()
 'two'
  instance_2 = instance_1
  instance_2.myName()
 'one'
Did you catch that ;-)

Ok, now without instance name bindings at all, just references from a list:
  egoes = [Ego(name) for name in 'one two three'.split()]
  egoes
 [__main__.Ego object at 0x02EF1A4C, __main__.Ego object at 0x02EF1A6C, 
__main__.Ego object
 at 0x02EF1A8C]
  for ego in egoes: print ego.myName()
 ...
 one
 two
 three

We don't have to access instance by names like instance_1, if we didn't make
them with bindings like that. E.g., egoes is a name bound to a list of Ego 
instances,
so we can get at the second (counting from index 0) instance thus, and change 
it's
name from the outside, since we know it's stored as an attribute called 'name':

  egoes[1].name = 'Zeppo'
  for ego in egoes: print ego.myName()
 ...
 one
 Zeppo
 three 

HTH

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list