Static method

mk mrkafk at gmail.com
Thu Feb 18 06:12:36 EST 2010


Hello everyone,

Disclaimer: I'm doing this mainly for learning purposes, to feel what 
it's good for.

I'm trying to get print_internal_date become a static method AND to 
refer to it in a class attribute 'tagdata' dict.

class PYFileInfo(FileInfo):
     'python file properties'

     @staticmethod
     def print_internal_date(filename):
         f = open(filename + 'c', "rb")
         data = f.read(8)
         mtime = struct.unpack("<i", data[4:])
         return time.asctime(time.gmtime(mtime[0]))

     tagdata = {'compiled_fname': lambda x: x + 'c',
                 'size': os.path.getsize,
                 'internal_date': print_internal_date
             }

     def __init__(self, fname=None):
         FileInfo.__init__(self,fname)

     def __setitem__(self, key, value):
         FileInfo.__setitem__(self, key, value)
         if key == 'name' and value:
             self.__get_props(value)

     def __get_props(self, value):
         py_compile.compile(value)
         for tag, fun in PYFileInfo.tagdata.items():
             self[tag] = fun(value)

But:

c:/Python26/pythonw.exe -u  "C:/mp3i/finfo2.py"
Traceback (most recent call last):
   File "C:/mp3i/finfo2.py", line 100, in <module>
     insts = list_dir(r'c:\mp3i',['.mp3', '.py'])
   File "C:/mp3i/finfo2.py", line 93, in list_dir
     insts = [c(f) for c,f in class_files]
   File "C:/mp3i/finfo2.py", line 69, in __init__
     FileInfo.__init__(self,fname)
   File "C:/mp3i/finfo2.py", line 12, in __init__
     self['name'] = filename
   File "C:/mp3i/finfo2.py", line 74, in __setitem__
     self.__get_props(value)
   File "C:/mp3i/finfo2.py", line 79, in __get_props
     self[tag] = fun(value)
TypeError: 'staticmethod' object is not callable


I think I know where the problem is: what resides in tagdata is a static 
method 'wrapper', not the function itself, according to:

http://docs.python.org/reference/datamodel.html

"Static method objects
     Static method objects provide a way of defeating the transformation 
of function objects to method objects described above. A static method 
object is a wrapper around any other object, usually a user-defined 
method object. When a static method object is retrieved from a class or 
a class instance, the object actually returned is the wrapped object, 
which is not subject to any further transformation. Static method 
objects are not themselves callable, although the objects they wrap 
usually are."

So, how do I get out the wrapped function out of static method without 
class call or instance call? (to be called in self[tag] = fun(value))

Yes, I do know that if I just get rid of @staticmethod, this works 
without a hitch.






More information about the Python-list mailing list