__init__.py file

Steven W. Orr steveo at syslang.net
Tue Apr 8 17:14:32 EDT 2008


On Tuesday, Apr 8th 2008 at 16:51 -0000, quoth cesco:

=>Hi,
=>
=>I need to instantiate an object (my_object) whose methods I have to
=>use in two files (file1.py and file2.py) which are in the same
=>directory. Is it possible to instantiate such object in the
=>__init__.py file and then directly use it in file1.py and file2.py?
=>If not, as I seem to experience, what is the best practice to follow
=>in this case? (I thought __init__.py was somehow useful for that).

Sounds more like a job for a singleton. I recently found one that I like a 
lot better than the standard recipe:

class Singleton(object):
    __single = None # the one, true Singleton
  
    def __new__(classtype, *args, **kwargs):
        if classtype != type(classtype.__single): 
            classtype.__single = object.__new__(classtype, *args, **kwargs)
        return classtype.__single
  
    def __init__(self,name=None):
        """Arg doesn't have to be str."""
        self.name = name
    
    def display(self):
        print self.name,id(self),type(self)

The advantage of this one is that it can be nicely subclassed.

if __name__ == "__main__":
  
    class SubSingleton(Singleton):
        def __init__(self, name=None):
            Singleton.__init__(self, name)
            self.aa = 123
            self.bb = 456
            self.cc = 789

    o1 = Singleton('foo')
    o1.display()
    o2 = Singleton('bar')
    o2.display()
    o3 = SubSingleton('foobar')
    o3.display()
    o4 = SubSingleton('barfoo')
    o4.display()
    print 'o1 = o2:',o1 == o2
    print 'o1 = o3:',o1 == o3
    print 'o3 = o4:',o3 == o4

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



More information about the Python-list mailing list