Part 1: import numpy as np¶
chances are you have seen us do the following at the top of our lectures/scripts/notebooks
import numpy as np
so what exactly are we doing here?
The import
keyword is used to tell Python that you want to bring in functionality from an external module.
This is the name of the module you want to import (in this case numpy
). A module is a Python file containing Python code and definitions. It can include variables, functions, and classes.
Finally you can use the as
keyword to give a module or an imported element a different name (an alias). This can be useful to avoid naming conflicts or to make the code more readable.
from now I can call the numpy package (and all its functions) using np
np.linspace(1,15,15) # for example
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13.,
14., 15.])
You can also write something like:
from module_name import function_name, class_name
where the function_name
or class_name
is specfic to the module you are trying to import!
you can also import everything using the *
wild card sybmol
from module_name import *
or use some combination of the syntax above
from module_name import element_name as alias
Part 2: where is the code?¶
If you are using “basic” packages like numpy
or math
, chances are you installed them when you installed python (via anaconda or something similar).
Those packages live in with your base install of python and can be called anywhere within your python environment.
If you want to use your own python modules, you need to make sure the script you are working with knows where they are.
The easiest way to do this is to have your scripts in the same directory. That way you can simply import any of them using the same commands that we just reviewed.
Otherwise, you might need to do something like:
import sys
sys.path.insert(0, '../src/')
import my_fav_module as yessir
this sys
import basically allows your current directory to know about the contents of the src
folder and import them as if they were in “local”
later on, we will briefly mention how to create packages out of your own code, in the same way that people share numpy