Importing two modules of same name
carl at oddbird.net
Tue Feb 9 18:36:41 EST 2016
On 02/09/2016 04:23 PM, Tim Johnson wrote:
> Before proceding, let me state that this is to satisfy my
> curiousity, not to solve any problem I am having.
> Scenario :
> Web application developed at /some/dir/sites/flask/
> If I have a package - let us call it app and in my
> /some/dir/sites/flask/app/__init__.py is the following:
> from config import config
> imports the config dictionary from /some/dir/sites/flask/config.py
> (the real-case scenario is M. Grinberg's tutorial on Flask).
> What if I wanted to add a module in the app package and call it from
> That entails having two modules name config
> one at /some/dir/sites/flask/config.py
> and the other at /some/dir/sites/flask/app/config.py
> What would be the proper way to do this? (If proper at all :)) I
> realize that it may not be best practices. And is a practice that I
> avoided in the past.
The proper way to do this in Python 2.7 is to place `from __future__
import absolute_import` at the top of flask/app/__init__.py (maybe best
at the top of every Python file in your project, to keep the behavior
consistent). Once you have that future-import, `import config` will
always import the top-level config.py. To import the "local" config.py,
you'd either `from . import config` or `import app.config`.
Python 3 behaves this way without the need for a future-import.
If you omit the future-import in Python 2.7, `import config` will import
the neighboring app/config.py by default, and there is no way to import
the top-level config.py.
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 836 bytes
Desc: OpenPGP digital signature
More information about the Python-list