Python projects are structured into modules.
There are a plethora of modules available in the Python standard library. Those are always available to you but you must import them.
Of course, you must also be aware of the fact that such a module exists. It is usually beneficial to be a bit lazy and assume someone has already solved your problem. Most of the time someone already has!
In [ ]:
import math
def circle_circumference(r):
return 2*math.pi*r
circle_circumference(3)
At it's simplest a module can just be a python file.
Let's create a file called mymodule.py in using jupyter (New -> Text File). Make sure to create the file in the same directory as this notebook. Edit the contents of the file to be:
def fancy_function(x):
return x + x
And save the file.
Now you can
In [ ]:
from mymodule import fancy_function
print(fancy_function(1))
print(fancy_function("hi"))
Modules can also have more structure in them. To make a directory a module, you must place a special file, called init.py in the directory.
main.py
bigmodule/
__init__.py
module_a.py
module_b.py
Now in main.py, you could import bigmodule.module_a.
It is also possible to import only a single member from a module, like a variable or a fuction.
In [ ]:
from math import exp
print(exp(1)) # which exponent is this
def circle_area(r):
if r < 0:
return 0
else:
# you can also import inside functions or other code blocks
from math import pi
return pi*r*r
print(circle_area(2))
Whether to import the entire module or only what you need depends on your circumstances and how the module has been designed to be used. It's usually good to pick a practice inside a project and stick to it.