weird behavior wrapping global functions into classes
Alex Martelli
aleaxit at yahoo.com
Thu Jun 14 10:19:26 EDT 2001
"Les Schaffer" <schaffer at optonline.net> wrote in message
news:0cahit44sql68p8pd2qgt59f600neha687 at 4ax.com...
> been losing sleep over this one...
>
> why does the following code successfully wrap the built-in open function
> into a class, but shelve's open method gets incorrectly (??) taken as an
> instance method? notice that everything works fine for the Flat version,
Whenever a function is accessed as an attribute of a class or
instance (and in the latter case, it's found in the class and
not in the instance itself), it's transmuted into a method
(unbound and bound, respectively). So, if you do need a callable
to NOT have method behavior, wrap the function in a non-function
callable; cfr., e.g.:
http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52304
for more discussion, but it boils down to:
class Callable:
def __init__(self, anycallable):
self.thecallable = anycallable
def __call__(self, *args, **kwds):
return self.thecallable(*args, **kwds)
and
> class NumFlat(NumStorage):
> mode = 'w'
> DB = 'flat.txt'
> #db = open(DB, mode)
> dbopen=open
change the last line into
dbopen = Callable(open)
Alex
More information about the Python-list
mailing list