Can't I define a decorator in a separate file and import it?

Marc Christiansen usenet at solar-empire.de
Thu Dec 22 16:26:02 EST 2011


Saqib Ali <saqib.ali.75 at gmail.com> wrote:
> I'm using this decorator to implement singleton class in python:
> 
> http://stackoverflow.com/posts/7346105/revisions
> 
> The strategy described above works if and only if the Singleton is
> declared and defined in the same file. If it is defined in a different
> file and I import that file, it doesn't work.
> 
> Why can't I import this Singleton decorator from a different file?

Maybe you're doing something wrong. But since you didn't provide any
code, it's impossible to tell what.

> What's the best work around?

As far as I can tell with the information you have given, none is
needed. See below:

0:> python2.7 singleton_test.py # works also with python3.2
Foo created
True
 
#singleton_test.py
from singleton import Singleton
# Singleton is the class from Paul Manta from the SO page
# and singleton.py contains nothing else

@Singleton
class Foo:
    def __init__(self):
        print('Foo created')

f = Foo.Instance()
g = Foo.Instance()

print(f is g)

Grüße
Marc



More information about the Python-list mailing list