Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Basic] Modules part 3
#1
Package Imports
Package imports are nothing more than a directory of imports. It turns a path on your computer into another namepsace, with attributes corresponding to the subdirectories and module files that the directory contains.
import dir1.dir2.mod
from dir1.dir2.mod import Klass
Here a directory named dir1, with a subdirectory named dir2, which in that has a module named mod.py (and the from statement indicates that mod.py has a Class named Klass, of which it imports). This indicates the directory structure in windows:
Quote:dir0\dir1\dir2\mod.py
The directory dir0 needs to be added to your module's search path (unless it's home directory of the top-level file).
You cannot use platform-specific path syntax, but only dotted (.) seporators. In Python 2.x, Each directory named within the path of a package import statement must contain a file named __init__.py, or your package import will fail. For example, dir1 and dir2 must both contain a file named __init__.py, the container dir0 does not because its not listed in the import statement. The structure would look like this:
dir0\
	dir1\
		__init__.py
		dir2\
			__init__.py
			mod.py
These __init__.py files can contain code, but they can be completely emtpy. These serve to prevent directories with common names from unintentionally hiding true modules that appear later on the module search path. Without this safe guard, python might pick a directory that has nothing to do with your code. The first time python imports through a directory, it automatically runs all the code in the directory's __init__.py file. These files are a place to put code to initialize the state required by files in a package. 

The __init__.py file is not required in Python3.x. Only Python2.x

Relative Imports
in Python 2.7 > and 3.x, you can use leading dots (.) to specify that they require modules located within the same package. This feature applies to only the from statement and only applies to imports within it's package.
in Python 2.6 < to apply this feature requires:
from __future__ import absolute_import
from . import mod
means import a module named mod located in the same package directory as the file in which this statement appears
from .mod import Klass
means from a module named mod located in the same package as the file that contains this statement, import the class Klass. This is a package import.
An import wihtout a leading dot always causes Python to skip the relative components of the module import search path and look instead in the absolute directories that sys.path contains. 
from .. import mod
equivalent to ../mod.py so to speak, from parent directory import module named mod

Quote: Relative imports are still possible by adding a leading period to the module name when using the from ... import form:

# Import names from pkg.string
from .string import name1, name2
# Import pkg.string
from . import string

This imports the string module relative to the current package, so in pkg.main this will import name1 and name2 from pkg.string. Additional leading periods perform the relative import starting from the parent of the current package. For example, code in the A.B.C module can do:

from . import D # Imports A.B.D
from .. import E # Imports A.E
from ..F import G # Imports A.F.G

Leading periods cannot be used with the import modname form of the import statement, only the from ... import form.

Mixed Usage __name__ and  '__main__'
This is a trick to let you both import a file as a module and run it as a standalone program.  Each module has a built-in attribute called __name__ which python sets as:
If the file is being run as a top-level program file, __name__ is set to the string "__main__" when it starts
If the the file is being imported instead, __name__ is set to the module's name as known by it's clients
It basically tests its own __name__ to see if it is being imported or ran.
The syntax:
if __name__ == '__main__':
	#put code here
Code in the if block will only execute if this file is being ran, not when this file is being imported. More examples can be found here

Importing by string
Sometimes you will need to get the name of the module to be imported as a string, in which case, you cannot:
>>> import 'sys'
  File "<stdin>", line 1
    import 'sys'
              ^
SyntaxError: EOL while scanning string literal
or you cannot:
>>> s = 'sys'
>>> import s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 's'
Python expects a varaible name for the first one and python atttmpts to import s.py on the second one. To account for this you can use the special tool to load a module dynamically from a string that is generated at runtime exec(). exec() compiles a string of code and passes it to python interpreter to be executed. 
>>> name = 'sys'
>>> exec('import {}'.format(name))
>>> sys
<module 'sys' (built-in)>
The other method is to use the built-in __import__ function, in which it returns the modules object
>>> sys = __import__('sys')
>>> sys
<module 'sys' (built-in)>
Naming your modules
You can name your modules anything you want. However if you name your modules the same name as modules in the standard library.... You will then importing your module and not the standard library's module. For example if i name a module ipaddress, os, sys, etc. Then by import os, or whatever, etc. I am importing my module instead of the standards library. Rename your module to something not in the standard library. This also applies to any 3rd party libraries you installed as well as built-in functions i would also avoid.
You can get a list of modules with 
>>> help('modules')
Go to Modules part 2
This tutorial was based off of Learning Python 4th Edition by Mark Lutz
Recommended Tutorials:


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Basic] Modules part 2 metulburr 1 6,669 Oct-03-2016, 09:48 PM
Last Post: metulburr
  [Basic] Modules part 1 metulburr 0 9,822 Sep-05-2016, 09:10 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020