I am writing my first python script and this package/module thing has me going nuts. Lets start with my folder layout
builder.py
-buildModule\__init__.py
-buildModule\AppList.py
-buildModule\BuildClass.py
-buildModule\ConfigSystem.py
-buildModule\MenuSystem.py
-buildModule\Singleton.py
ok, so my __init__.py looks like this
from ConfigSystem import *
from BuildClass import *
from MenuSystem import *
from AppList import *
from buildModule.Singleton import Singleton
Now, im trying to decorate my configsystem as a singleton so my singleton looks like
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.')
and now, with my configsystem class, if im reading the manual correctly, this should work
import Singleton
@Singleton
class ConfigSystem:
but im getting
TypeError: 'module' object is not callable
I've read the module part of the manual several times now and im not quite getting it. Why isn't this working?
Is there a module/package tutorial out there somewhere that is written a bit clearer/differently than the manual?
2 Answers 2
You need to change import Singleton to from Singleton import Singleton (or as Alex suggested change @Singleton to @Singleton.Singleton.
In general you should use qualified imports to avoid namespace collisions, e.g., import SomeModule with a call like SomeModule.SomeClass or for brevity something like import SomeModule as SM with a call like SM.SomeClass or SM.some_function rather than importing everything from a module like from SomeModule import *.
You have name collisions, where Singleton is referring to the module (e.g., Singleton.py a file that is a collection of classes/functions/variables) rather than the Singleton class (class Singleton(object)). Specifically, in your decorator @Singleton Singleton is referring to the module (you import some_module or from some_module import a_class_or_object) rather than a class or function.
Comments
Either change import Singleton to from Singleton import Singleton, or change @Singleton to @Singleton.Singleton.
ConfigSystemthe name of a module AND the name of a class? Isn't that going to be confusing? Could you change one of those names? It would almost eliminate your'module' object is not callableerror.