Bug or wart? You make the call.

Alex A. Naanou alex_nanou at pochtamt.ru
Sat Mar 8 10:33:18 EST 2003


Jp Calderone <exarkun at intarweb.us> wrote in message news:<mailman.1047068354.22570.python-list at python.org>...
> On Fri, Mar 07, 2003 at 10:05:24AM -0800, Inyeol Lee wrote:
> > On Thu, Mar 06, 2003 at 12:14:44AM -0500, Terry Reedy wrote:
> > > 
> > > [snip]
> > > 
> > > Try Spam.  dict  ['eggs'] without assignment, as you did with
> > > 'Spam.eggs' above and see what type of object you are assigning to.
> > > This should  answer your question.
> > 
> > I'm a little bit confused. It seems that we cannot add arbitrary
> > attributes to class methods, but can add them to functions. Is it
> > correct? Is there any specific reason for this difference?
> 
>   There is one very practical reason.  Method objects (not "class methods" -
> those are something else) are created anew every time they are fetched!  Any
> attributes you set on them won't be there the next time you grab the method
> object.
> 
>   You can see this behavior for yourself:
> 
>     >>> class foo:
>     ...   def bar(): pass
>     ...
>     >>> f = foo()
>     >>> a, b = f.bar, f.bar
>     >>> id(a), id(b)
>     (136028180, 136028220)
> 
>   To toss in my 2c, state belongs on "f" anyway, not on f's methods.
> 
>   Jp

Why not proxy attribute creation to the wrapped object?
  I do find the current state strange and inconsistent...

Example:

---cut---
class X(object):
    def meth(self):pass

x = X()

# the ways to go in the current state:
# proposed above:
x.__dict__['xx'].attr0 = 0
X.__dict__['xx'].attr1 = 1

# another way that works:
x.meth.__setsttr__('attr2', 2)
X.meth.__setsttr__('attr3', 3)

print x.meth.attr0, x.meth.attr1, x.meth.attr2, x.meth.attr3
# will print "0 1 2 3"

# so why not make this work as well:
## x.meth.attr4 = 4

---uncut---

                                              Best Regards...
                                                        Alex.




More information about the Python-list mailing list