Question

Is it possible to override a module with a class ?

Let me explain,

Here is the filesystem

foo
|-- bar
|   |-- __init__.py
|   |-- config.py
|-- __init__.py

Is it possible to override config.py from foo.bar.__init__.py so that whenever someone imports foo.bar.config they are importing overriden config instead of the version from config.py ?

If yes how do I do it ?

Ps: I will be overriding config.py based on certain conditions.

Was it helpful?

Solution

Just define a class in foo/bar/__init__.py with the name config and that will be imported. But why don't you just change the config.py?

In [4]: !ls foo
__init__.py   bar/
In [5]: !ls foo/bar
__init__.py   config.py
In [6]: !cat foo/bar/__init__.py
class config(object):
    pass
In [7]: from foo.bar import config    
In [8]: type(config)
Out[8]: type

$ echo "" > foo/bar/__init__.py
$ ipython

In [1]: from foo.bar import config    
In [2]: type(config)
Out[2]: module
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top