1

i am trying to import a module within a module and then access the lower level module from the top, however it is not available. is this normal behaviour?

# caller.py
import first
print second.some_var

# first.py
import second

# second.py
some_var = 1

running caller.py gives error

NameError: name 'second' is not defined

do i have to import second within caller.py? this seems counter-intuitive to me.

1
  • Circular imports can lead to annoying problems, so it would be better to avoid this kind of import pattern. If both first and second need access to some_var, you could create third module and put some_var in there. Commented Nov 16, 2013 at 0:36

3 Answers 3

3

You can use

import first
print first.second.some_var

Having second appear in the namespace automatically just by importing first would lead to lots of conflicts

This would also work

from first import second
print second.some_var

The use of wildcard

from first import *

is discouraged because if someone adds extra attributes/functions to first they may overwrite attributes you are using locally if they happen to choose the same name

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for explaining why the wildcard is discouraged
1

import first will import the name first into the global namespace, but it does not import everything from first into the namespace. So you can do one of the following:

  • Access second through first:

    import first
    print first.second.some_var
    
  • Import second directly into the namespace of caller.py:

    from first import second
    print second.some_var
    

Note that you can use from first import * to import all of the names from first into the namespace, but this is generally discouraged.

Comments

0

instead use:

from first import second
print first.second.some_var

It is a lot more compressed too. Why are you doing your way anyway?

1 Comment

basically i have common library files which i use in a lot of projects (many files with the role of 'second' in this example) and then i have higher level library files per project (ie many files with the role of 'first' in this example). so each project only needs to know about 'first', and 'first' only needs to know about 'second'. i know a class structure with first extends second would be ideal, but i'm just trying to see if i can use modules and avoid classes...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.