I am trying to decorate the magic method __getitem__
to be a classmethod on the class. Here is a sample of what I tried. I don't mind using either classmethod or staticmethod decoration, but I am not too sure how to do it. Here is what I tried:
import ConfigParser
class Settings(object):
_env = None
_config = None
def __init__(self, env='dev'):
_env = env
# find the file
filePath = "C:\\temp\\app.config"
#load the file
_config = ConfigParser.ConfigParser()
_config.read(filePath)
@classmethod
def __getitem__(cls, key):
return cls._config.get(cls._env, key)
@classmethod
def loadEnv(cls, env):
cls._env = env
However, when I try to call Settings['database']
I get the following error.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected Array[Type], got str
Can anyone tell me what I am doing wrong. Also, could someone suggest if there is better way to do this? I even tried using MetaClasses, but with little success (as I don't know python too well).
class Meta(type):
def __getitem__(*args):
return type.__getitem__(*args)
class Settings(object):
__metaclass__ = Meta
Thanks in advance.
Apart from Alex's (entirely correct) answer, it isn't clear what you actually want to do here. Right now you are trying to load the config when you instantiate the class. If you were to assign that _config to the class object, that would mean all instance of the class share the same config (and creating another instance would change all existing instances to point to the latest config.) Why are you trying to use the class to access this configuration, instead of a particular instance of the class? Even if you only ever have one configuration, it's much more convenient (and understandable!) to use an instance of the class. You can even store this instance in a module-global and call it 'Settings' if you like:
class _Settings(object):
def __init__(self, fname):
self._config = ...
...
Settings = _Settings('/path/to/config.ini')