[Python-Dev] Arbitrary attributes on funcs and methods
Barry A. Warsaw
bwarsaw@cnri.reston.va.us
Wed, 12 Apr 2000 14:19:47 -0400 (EDT)
>>>>> "MZ" == Moshe Zadka <moshez@math.huji.ac.il> writes:
>> so? you can use methods as keys today, you know...
MZ> Actually, I didn't know. What hapens if you use a method as a
MZ> key, and then change it's doc string?
Nothing.
Python 1.5.2 (#7, Apr 16 1999, 18:24:22) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def foo():
... 'a doc string'
...
>>> d = {}
>>> d[foo] = foo
>>> foo.__doc__ = 'norwegian blue'
>>> d[foo].__doc__
'norwegian blue'
The hash of a function object is hash(func_code) ^ id(func_globals):
Python 1.6a2 (#26, Apr 12 2000, 13:53:57) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def foo(): pass
...
>>> hash(foo)
557536160
>>> hash(foo.func_code)
557215928
>>> id(foo.func_globals)
860952
>>> hash(foo.func_code) ^ id(foo.func_globals)
557536160
So in the words of Mr. Praline: The plumage don't enter into it. :)
But you can still get quite evil:
Python 1.6a2 (#26, Apr 12 2000, 13:53:57) [GCC 2.8.1] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def foo(): pass
...
>>> def bar(): print 1
...
>>> d = {}
>>> d[foo] = foo
>>> d[foo]
<function foo at dee08>
>>> foo.func_code = bar.func_code
>>> d[foo]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: <function foo at dee08>
Mwah, ha, ha!
Gimme-lists-as-keys-and-who-really-/does/-need-tuples-after-all?-ly y'rs,
-Barry