The import command in Python is one of my favorites (not joking). import allows the programmer to link (load) files and inherit all of the contents of that file (you can use whatever is in that file in another file). Here is the basic syntax:
import [module]
[module] is also called a file, but they’re referred to as modules. I’ll explain modules a little later. A little note: Python will execute whatever is in the file if it can. Meaning, you cannot store a file in a variable this way. It’d be like storing a file in a variable by using #include (C++) or require (PHP). Also, it must be a Python file (.py) and you do not include the extension (why is also explained). Finally, import loads the modules that the current file is in; for example, if you import a module and the file is the directory C:\Testing\Build, then Python will load (and execute) C:\Testing\Build\[module_name].
Ok, so say you don’t want to load the entire file. What is there to do? You can load a class from the file, like so:
from [module] import [class]
This means, from the module that is [module] only take the class that is [class]. Meaning, if you do this,
from foo import bar
Python will load bar from foo and only bar from foo. It won’t load anything else. You can use multiple classes as well,
from foo import bar, stool
Python will load only bar and stool from the module that is foo. Likewise, you can load multiple modules as well,
import foo, settings
However, you cannot do this,
from foo, settings import bar, UI
This will generate a syntax error, the most common error. Now, onto modules. A module is anything with Python code in it – that includes folders. Python supports folders acting as modules. How is this done? Like this,
import [folder_name]
The only difference is that there needs to be a __init__.py file in [folder_name]. Otherwise, Python will think the module doesn’t exist. Why would you want to do this? Mainly for organization. You can do this,
import [folder_name].[module]
Python will load [module] that’s in [folder_name]. Meaning, you can do this,
import source.settings
and Python will load the file source/settings.py. As long as there’s a source/__init__.py file, it’ll work. In fact, you can even do this,
from source import settings
and it’ll work. You cannot do this:
import source/settings
You’ll get a syntax error. You especially should not do this:
import source\settings
That’s just plain stupid and one of the worst syntax errors one can make.

No comments yet
Comments feed for this article