If you type python3
on the command line of a terminal, without any arguments, you will start a Python interpreter in interactive mode. It lets you type your python statements, and run them one after the other.
When you simply type the name of a variable, the interactive interpreter displays its value.
text = "Hello World !"
text
'Hello World !'
This interactive mode is only ok for basic tests, using existing functions and libraries. As soon as you want to write reusable code, put it in a separate file, called a script, and run it with a simple command python3 myscript
. To emphasize your file contains some python code, it is recommended to use a file name ending with .py
.
%%writefile my_script.py
text = "Hello World !"
print(text)
Writing my_script.py
!python3 my_script.py
Hello World !
When not in interactive mode, whenever you want to display something on the terminal, you must call the function print()
.
So to make your script directly executable, without the need to explicitly call python3
, it is common practice to add a "shebang" line at the beginning of your script and make the file executable:
%%writefile my_script.py
#!/usr/bin/env python3
text = "Hello World !"
print(text)
Overwriting my_script.py
!chmod a+x my_script.py
!./my_script.py
Hello World !
Finally, Python 3 requires that your files are encoded with UTF8, and it is a good pratice to a special comment as second line in your file, so to instruct your editor about this encoding:
%%writefile my_script.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
text = "Hello World !"
print(text)
Overwriting my_script.py
!./my_script.py
Hello World !
There are some utility functions that you will want to reuse in several scripts. Rather than copy-paste this common code in every script, you should better store it in a separate file, whose name MUST end with .py
, and "include" it in your scripts. Python call this sort of file a module, and the inclusion mechanism rely in the import
statement.
The first time one import a module my_module
, the interpreter will:
my_module.py
in the sequence of directories given by sys.path
:PYTHONPATH
,my_module.py
into __pycache__/my_module.pyc
, if the latter is out of date ;my_module.pyc
, storing any global variable and function into a object referenced by the variable my_module
.%%writefile my_module.py
# -*- coding: utf-8 -*-
text = "Hello World !"
def say_hello():
print(text)
Writing my_module.py
import my_module
print(my_module.text)
my_module.say_hello()
Hello World ! Hello World !
If one imports a second time the same module, the interpreter reuse the previously built object. That is, if you changed something in the imported code, it will not be taken into account.
%%writefile my_module.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
text = "hello world !"
def say_hello():
print(text)
Overwriting my_module.py
import my_module
print(my_module.text)
my_module.say_hello()
Hello World ! Hello World !
Warning : while you are developing some modules, it is not recommended to use an interpreter in interactive mode, because the interpreter do not automatically detect when you modify a module source code, and blindly reuse the old version. It is a lot safier to rerun from scratch your main script each time you want to see the effect of your last modifications to any module file.
%%writefile my_script.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import my_module
print(my_module.text)
my_module.say_hello()
Overwriting my_script.py
!./my_script.py
hello world ! hello world !
When you feel the name of the module is too long, you can change the name of the variable which refers to it. It does not anything about the search, compilation and execution of the module file and object. Only the variable name is changed.
%%writefile my_script.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import my_module as mm
print(mm.text)
mm.say_hello()
Overwriting my_script.py
!./my_script.py
hello world ! hello world !
If you want to completely avoid to type the name of the module, you can use the from
statement so to create variables that refers directly to attribues of the module objects. Again, it does not anything about the search, compilation and execution of the whole module file and object. But instead of a variable which refers to the whole module object, you will obtain variables refering to its individual elements:
%%writefile my_script.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from my_module import text, say_hello
print(text)
say_hello()
Overwriting my_script.py
!./my_script.py
hello world ! hello world !
Worth to note, import
and from
are usual assignment statements:
sys.path
can be redefined anywhere in the code, and this will affect subsequent import
.Warning : you may encounter the statement from my_module import *
, which generate a variable for every attribute of the module. It is a bad practice, especially for big modules, because you rarely know the complete list of variables to be created, and one of them could secretly overwrite one of your other variables.
When you have many functions to reuse, you distribute them in several modules. Once you have many such modules, you may want to organize them into several directories. A set of module files, grouped into a directory, is called a package.
The simpler way to import a module from a package is to use import my_package.my_module
. As one can guess, the interpreter will first search for a directory called my_package
within the directories of sys.path
, then it will proceed as usual for the module. Access to the elements is going through the extended prefix my_package.my_module.
.
!mkdir my_package
%%writefile my_package/my_module.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def say_hello():
print("Hello world !")
Writing my_package/my_module.py
import my_package.my_module
my_package.my_module.say_hello()
Hello world !
The usual modifier as ...
is usable, and also the statement from
. The latter can be used to import a module from a package a create a variable pointing directly to
import my_package.my_module as mm
mm.say_hello()
Hello world !
from my_package import my_module
my_module.say_hello()
Hello world !
from my_package.my_module import say_hello
say_hello()
Hello world !
The standard library of Python provides you with many packages and modules.
Of course, you will quickly ends with scripts which include modules, which includes modules, which includes modules, etc. Whatever the context, for a given interpreter session, each module will only be loaded once. The subsequent import
commands will only add additional variables refering to the module already in memory, or some of its attributes.