# Importing in Python

## Contents

# Importing in Python#

Programming for Geoscientists Data Science and Machine Learning for Geoscientists

Python’s growing popularity over the years has inevitably lead to the development of thousands of excellent libraries and python-based frameworks. This section will cover the basics of importing them, but also cover how to import your own classes, functions and much more.

Often we will want to import many functions and objects from a certain module, so we would simply import the entire module:

```
import math
print(math.sin(0))
```

```
0.0
```

Importing the whole math module allows us to use everything inside it, such as the `sin`

function. However, if we only need the `sin`

function from the math module, it is good practice to import only that.

```
from math import sin
print(sin(0))
```

```
0.0
```

When imported like this, we no longer need to use the `math.`

prefix, because this also imported `sin`

into our namespace. If we instead do:

```
from math import *
print(cos(0))
```

```
1.0
```

Here we have imported everything from the math module **and** we put everything from it into our namespace. This is generally **not** recommended, as it can overshadow our other functions with the same name. The same can happen if we import a single function. We can avoid this by renaming our imports.

```
import numpy as np
from math import sqrt as square_root
print(square_root(4))
print(np.ones(5))
```

```
2.0
[1. 1. 1. 1. 1.]
```

If we want to import a function from a specific file, say a file named `my_module.py`

and it is located in the same folder as the python script into which we want to import it, we simply write:

```
from my_module import my_function
print(my_function(3))
```

```
9
```

Where `my_function`

is just a square in this case. In general, we can specify a path to our module. For example, if our `my_module.py`

file is on our Desktop, we could import it with:

```
import os
os.chdir(r'C:\Users\StudentShapers\Desktop')
import my_module
```

## Exercises#

**Choose your function!**Mike decides to play a bit with Python functional interface and module importing, so he creates a strange list:

```
f = [math.sin, math.cos,math.tan, math.log, random.randrange]
```

He wants to create a program which will take (at random) a function from the list and apply it to the number \(a\). The process should be repeated \(n\) times. Help Mike!

Answer

```
import math
import random
f = [math.sin, math.cos, math.tan, math.log, random.randrange]
a = 4
n = 10
for i in range(n):
j = random.randint(0,len(f)-1) # random int between 0 and len(f)-1
# print the name of function, a and result in an f-string
print(f"{f[j].__name__}({a}) = {f[j](a)}")
# to print just the result: print(f[j](a))
```