HongboZhu
HongboZhu

Reputation: 4532

different import results at different directories

I have a package MyPak and a module MyMod. The files are organized in the following way:

somedir/MyPak/MyMod.py

in MyMod.py there is only a Class whose name is also MyMod

in directory somedir/MyPak, if I do the import:

import MyMod

I got MyMod imported as a Module.

But in directory somedir/, if I do

from MyPak import MyMod

I got MyMod imported as a Class, not a Module. Why is this the case?

Upvotes: 4

Views: 363

Answers (1)

Nate
Nate

Reputation: 12839

This behavior is indicative that you have a file:

somedir/MyPak/__init__.py

wherein you do the following:

from MyMod import *

When you import MyPak, it imports from that __init__.py - likewise, when you from MyPak import something, it's going to try to pull from the namespace for the package - which will look inside that __init__.py

Because you imported everything from MyMod inside __init__.py, now the class is local to the MyPak package, and masks the MyMod.py file.

Upvotes: 4

Related Questions