How to import a module from the root dir having another with same name in a descendent package?
Question: I'm using python 2.7.10.

I understand that there is many questions related to this. I'm starting this
question because none of answers I found in StackOverflow answers my doubts.
My goal here is to clarify my understanding about the Python import machinery
with the help of the community.

I have a project with a structure like this:

    
    
    ./
    ./config.py
    ./modules
    ./modules/__init__.py
    ./modules/config.py
    

**config.py**

    
    
    VALUE = 1
    

**modules/config.py**

    
    
    import config
    print(config.VALUE)
    

In this module, I want to get the VALUE constant from the module in the root
dir and print it. When I run the config in modules package I get the following
error:

    
    
    $ python modules/config.py
    Traceback (most recent call last):
      File "modules/config.py", line 1, in <module>
        import config
      File "/test/modules/config.py", line 2, in <module>
        print(config.VALUE)
    AttributeError: 'module' object has no attribute 'VALUE'
    

I understand that the **import config** statement imports the module in the
current directory instead the one in the root dir. So I need to add a _kind of
hack_ to allow it import the module in the root dir:

**modules/config.py**

    
    
    def import_from_root(name):
        import os
        import imp
        root_path = os.path.dirname(os.path.abspath(__name__))
        root_module = os.path.join(root_path, '{}.py'.format(name))
        return imp.load_source('root_'.format(name), root_module)
    
    print(import_from_root('config').VALUE)
    

Now it works:

    
    
    $ python modules/config.py
    1
    

But I'm wondering if this is the best way to do this. So, I have the following
questions:

  1. Is there a more pythonic way to solve this?
  2. To move to Python 3.x will improve this?

Please, consider that I don't want to change the directory structure or the
names of the modules.


Answer: This works if you'd rather change your current working directory than your sys
path:

    
    
    from os import chdir
    chdir('/')
    import config
    

this might be better if you have other resources in root. Both this and the
above solution are more parsimonious and pythonic than your current solution.

