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

S

Saqib Ali

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?
What's the best work around?
 
E

Ethan Furman

Saqib said:
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?
What's the best work around?

Post the code, and the traceback.

~Ethan~
 
S

Saqib Ali

BTW Here is the traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "myClass.py", line 6, in <module>
@Singleton
TypeError: 'module' object is not callable



Here is Singleton.py:



class Singleton:

def __init__(self, decorated):
self._decorated = decorated

def Instance(self):
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance

def __call__(self):
raise TypeError(
'Singletons must be accessed through the `Instance`
method.')



Here is myClass.py:

#!/usr/bin/env python
import os, sys, string, time, re, subprocess
import Singleton


@Singleton
class myClass:

def __init__(self):
print 'Constructing myClass'

def __del__(self):
print 'Destructing myClass'
 
E

Ethan Furman

Saqib said:
MYCLASS.PY:

#!/usr/bin/env python
import os, sys, string, time, re, subprocess
import Singleton

This should be 'from Singleton import Singleton'

@Singleton
class myClass:

def __init__(self):
print 'Constructing myClass'

At this point, the *instance* of myClass has already been constructed
and it is now being initialized. The __new__ method is where the
instance is actually created.
def __del__(self):
print 'Destructing myClass'


class Singleton:

def __init__(self, decorated):
self._decorated = decorated

def Instance(self):
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance

def __call__(self):
raise TypeError(
'Singletons must be accessed through the `Instance`
method.')


~Ethan~
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top