Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -- import the package in a module that is inside the same package

Tags:

python

I have a project structure something like this...

/some_app     build/     README     out.py     some_app/         __init__.py         mod1.py         mod2.py 

Now I want to import some_app package into mod2, without messing with sys.path trickery. What I simply did is...

# mod2.py import some_app 

Now when I run the mod2.py from the command line

some_app $ python mod2.py 

it throws error ImportError: No module named some_app

BUT, inside the out.py file, when I do

# out.py import some_app.mod2 

and then do

some_app $ python out.py 

it runs perfectly.

Hence, what is happening is this. I load a package in a module that is within the same package, and then run that module as the __main__ file -- and it doesn't work. Next, I load the same module (the one that I ran as __main__) inside another module, and then run that another module as __main__ -- and it works.

Can someone please elaborate on what's going on here?

UPDATE

I understand that there is no straightforward reason for doing this -- because I could have directly imported any modules inside the some_app package. The reason I am trying this is because, in the Django project, this is what they're doing. See this file for example

In every module, all the non-standard imports start with django.. So I wondered why and how they are doing that.

UPDATE 2

Relevant links

  • How to do relative imports in Python?
  • Python: import the containing package
like image 454
treecoder Avatar asked May 18 '12 06:05

treecoder


People also ask

Can you have a module within a module Python?

Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

Can we import same package twice in Python?

Yes, you can import a class twice in Java, it doesn't create any issues but, irrespective of the number of times you import, JVM loads the class only once.

How do you import a module from a package?

Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.


1 Answers

mod2.py is part of some_app. As such, it makes no sense to import the module, since you're already inside it.

You can still import mod1. I'm assuming you need some_app/__init__.py to run. Not sure that's possible.


EDIT:

Looks like from . import some_module will do what you're after.

like image 180
Eric Avatar answered Oct 12 '22 23:10

Eric