mulllhausen
mulllhausen

Reputation: 4435

python import within import

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.

Upvotes: 1

Views: 137

Answers (3)

user2884344
user2884344

Reputation: 205

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?

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208665

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.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304463

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

Upvotes: 3

Related Questions