Python - import

Folks,

Been out of the programming loop for years but starting to look at python.

Can someone clarify; when the code says import ‘something’ where is that being imported from, is it all in the directory structure of python?

Geffers

Python will happily tell you the answer to this, fire up a repl (just type python in the terminal) and run:

import sys
>>> sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-arm-linux-gnueabihf', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old' ... etc

You will see a list of all the paths that Python looks in for modules.

If you’re spreading your code into several files, note that Python can only import modules from the base dir. IE if your directory tree is:

- main.py
- mymodule.py

Then you will be able to import mymodule

However if it’s:

- main.py
- test
   - mymodule.py

You will not. And you will not be able to import test.mymodule or from mymodule import test either.

However you can tell Python that your folder is a “package” (a collection of modules) by placing an __init__.py in there:

- main.py
- test
  - __init__.py
  - mymodule.py

And now suddenly you can from temp import mymodule

You can actually explicitly import a module by full path, but you should never need to: https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path

1 Like

Thank you, good explanation.

Geffers