weird behavior wrapping global functions into classes

Les Schaffer schaffer at optonline.net
Thu Jun 14 08:26:12 EDT 2001


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,
built-in open is called correctly, but the __init__ fails for the Shelf
version, since it thinks self.dbopen is now an instance method.

==== my output: ===
up here, open =  <built-in function open>
up here, shelf_open =  <function open at 00952924>
in NumFlat class definition, dbopen =  <built-in function open>
in NumShelf class definition, dbopen =  <function open at 00952924>
but over here self.dbopen =  <built-in function open>
but over here self.dbopen =  <method NumShelf.open of NumShelf instance at
0095237C>

Traceback (most recent call last):
... 
=== huh???? ===

weird: self.dbopen knows its the built-in open for the NumFlat case, but
gets screwed up in the NumShelf case.

what terrible thing have i done? thanks

les schaffer

p.s. purpose of code was to fool around to see differences in disk space for
pickling numeric arrays vs. writing them out flat.

============
from Numeric import arange, Float32, array2string, cos
from shelve import open as shelf_open

print 'up here, open = ', open              # all ok
print 'up here, shelf_open = ', shelf_open  # all ok
 
class NumStorage:

    def __init__(self):
        tup = (self.DB,)
        if self.mode:
            tup += (self.mode,)

        print 'but over here self.dbopen = ', self.dbopen # huh???

        self.db = apply(self.dbopen, tup)

    def close(self):
        self.db.close()
        
class NumFlat(NumStorage):
    mode = 'w'
    DB = 'flat.txt'
    #db = open(DB, mode)
    dbopen=open
    print 'in NumFlat class definition, dbopen = ', dbopen # ok
    
    def store(self, key, value):
        self.db.write(array2string(value, precision=8))

class NumShelf(NumStorage):
    mode = None
    DB = 'test.dbm'
    #db= shelf_open(DB)
    dbopen=shelf_open
    print 'in NumShelf class definition, dbopen = ', dbopen # ok

    def store(self, key, value):
        self.db[key] = value


## space test ##    
nf = NumFlat()
ns = NumShelf()

x = arange(0,1.0,.01, Float32)
x = cos(x)
for i in range(10):
    key = '%d'%i
    ns.store(key, x)
    nf.store( key,x )

ns.close()
nf.close()




More information about the Python-list mailing list