function attributes are like function objects
Fredrik Lundh
fredrik at effbot.org
Sat Feb 3 07:40:58 EST 2001
Tim Peters wrote:
> Yes, and if you *showed* that one-liner, the "easier" would be shot all to
> pieces. These aren't meant to be write-only attributes <wink>.
here's how I would solve your publishing example:
ALWAYS = "ALWAYS"
SOMETIMES = "SOMETIMES"
#
# user code
class ClassicSpam:
publish = {}
def egg(self, x):
pass
publish[egg] = ALWAYS
# 2.1: egg.publish = ALWAYS
class NewSpam(ClassicSpam):
publish = {}
def bacon(self, x):
pass
publish[bacon] = SOMETIMES
# 2.1: bacon.publish = SOMETIMES
#
# code for the publisher framework
def getpublish(klass, name):
# figure out if/when we can publish this method
try:
method = getattr(klass, name)
return method.im_class.publish[method.im_func]
# 2.1: return method.publish
except (AttributeError, KeyError):
return None # nope
#
# try it out
for function in ["bacon", "egg", "spam"]:
print function, getpublish(NewSpam, function)
advantages:
+ works with pre-2.1 python
+ requires one dictionary per class instead of one
per method
+ no memory penalty for classes that doesn't belong
to the publishing framework
disadvantages:
+ the 1-3 lines you need to dig out the attribute
varies slightly, depending on the application
> > On the other hand, this isn't such a big deal, especially not com-
> > pared to some of the stuff I've seen on python-dev lately. I'm
> > pretty sure a third-party python implementer can ignore function
> > attributes, and nobody will ever notice...
>
> We would certainly notice the absence of function.__doc__,
> and any 3rd-party implementer realizing that first would likely
> take a much more uniform approach to implementing object
>> attributes than did Guido at the start.
not so sure about that -- __doc__ strings are very common,
and are better stored in a separate slot to save memory (just
like CPython does, of course).
and I doubt many people would notice if __doc__ were made
readonly...
Cheers /F
More information about the Python-list
mailing list