Python — Modules and packages

Python — Modules and packages

vvrubel

Track content


Load module

§1. Module basics

While working on simple examples you probably type your code directly into the interpreter. But every time you quit from the interpreter and start it again you lose all the definitions you made before. So as you start writing larger programs it makes sense to prepare your code in advance using a text editor and then run it with the interpreter. A file containing a list of operations that further are read and interpreted is called script.

You also may want to write some functions and then use them in other programs or even reuse code someone else wrote before. One way is just to copy the code into your program, but it soon leads to code that is bad-structured and hard to read. Luckily, there is another way in Python to organize and reuse code called modules.

The module is simply a file that contains Python statements and definitions. It usually has a .py extension. What really makes the module system powerful is the ability to load or import one module from another.

§2. Module loading

To load a module just use an import statement. In a basic form, it has the following syntax import module.

import super_module

super_module.super_function()  # calling a function defined in super_module

print(super_module.super_variable)  # accessing a variable defined in super_module

super_module is the name of the module you want to import. For example, a file called super_module.py has a name super_module. In order to be available for import, super_module.py should be located in the same directory as the file you are trying to import it from.
At first, Python importing system looks for a module in the current directory, then it checks the built-in modules, and if nothing is found an error will be raised.
After importing, the module becomes available under its name and you can access functions and variables defined in it using the dot notation.

It's also common to only import required functions or variables from a module but not the module itself. You can do this by using a from form of import statement.

from super_module import super_function

super_function()  # super_function is now available directly at the current module

super_module.super_function()  # note, that in this case name super_module is not imported, 
                               # so this line leads to an error

A good practice is to load a single module in a single line and put all your imports at the top of the file because it increases readability.

import module1
import module2
import module3

# the rest of module code goes here

A special form of import statement allows you to load all the names defined in a module. It is called wildcard import and has syntax from module import *. You should generally avoid this in your code. It can cause unexpected behavior because you don't know what names exactly are imported into the current namespace. Besides, these names may shadow some of the existing ones without your knowledge. It's better to make it explicit and specify what you're importing.

In case you have to use several import statements, pay attention to their order:

  1. standard library imports
  2. third party dependency imports
  3. local application imports

Having your imports grouped, you may put a blank line between import sections. Also, some guidelines, including ours, recommend sorting imports alphabetically.

§3. Built-in modules

Python comes with a great standard library. It contains a lot of built-in modules that provide useful functions and data structures. Another advantage is that the standard library is available on every system that has Python installed. Here you can find an official library reference.

Python has a math module that provides access to mathematical functions.

import math

print(math.factorial(5))  # prints the value of 5!

print(math.log(10))  # prints the natural logarithm of 10

print(math.pi)  # math also contains several constants
print(math.e)

string module contains common string operations and constants.

from string import digits

print(digits)  # prints all the digit symbols

random module provides functions that let you make a random choice.

from random import choice

print(choice(['red', 'green', 'yellow']))  
# print a random item from the list




Up!

Math functions

We already learned how to perform basic arithmetics in Python. We covered addition, subtraction, multiplication, division and several other built-in operations. But if we want to do more complex operations on numbers we can use built-in mathematical functions or functions from the math module.

math module provides useful mathematical functions and constants. This module is available on every platform in the standard library.

§1. Advanced arithmetics

There are built-in functions abs, round, pow, max and min:

  • abs(x) returns the absolute value of (i.e. value without a regard to its sign);
  • round(x, ndigits) returns rounded to ndigits number of decimal part digits;
  • pow(x, y) returns raised to the power of y;
  • max(a, b, c, ...) returns the largest argument;
  • min(a, b, c, ...) returns the smallest argument.
abs_integer = abs(-10)  # 10
abs_float = abs(-10.0)  # 10.0

round_integer = round(10.0)      # 10, returns integer when ndigits is omitted
round_float = round(10.2573, 2)  # 10.26

pow_integer = pow(2, 10)  # 1024
pow_float = pow(2.0, 10)  # 1024.0

largest = max(1, 2, 3, 4, 5)   # 5
smallest = min(1, 2, 3, 4, 5)  # 1

abs() and pow() functions have equivalents in the math module. The key difference of math.fabs() and math.pow() is that they always return floats:

import math

fabs_integer = math.fabs(-10)  # 10.0
fabs_float = math.fabs(-10.0)  # 10.0

pow_integer = math.pow(2, 10)  # 1024.0
pow_float = math.pow(2.0, 10)  # 1024.0

Remember that in order to use definitions from math, you should import the module first.

Suppose you raised x to the power y, and then forgot y. You can recover it using the math.log() function:

import math

x = 2
y = 10
pow = math.pow(x, y)    # 1024.0
log = math.log(pow, x)  # 10.0

math.log(pow, x) returns z such that x raised to the power z equals pow. If the second argument x (called the base of the logarithm) is omitted, it is considered equal to a special number (approximately 2.718):

import math

natural_log = math.log(1024)  # 6.931471805599453 

Besides the round() function, we can use floor() and ceil() from the math module to obtain integer values from floats:

  • math.floor(a) returns the nearest integer less than or equal to a;
  • math.ceil(a) returns the nearest integer greater than or equal to a.

The math module also provides the sqrt function to calculate the square root of a number.

import math

result = math.sqrt(100)  # 10.0

§2. Geometry

The number π is often used in geometry and other mathematical fields. It is the ratio of the circumference of a circle to its diameter.
It can be found in the math module as pi.

The next example shows how to calculate the circumference of a circle:

import math

r = 3.5
circumference = 2 * math.pi * r  # 21.991...

There are also common trigonometric functions available in the math module:

  • math.cos(a) returns the cosine of radians;
  • math.sin(a) returns the sine of a radians;
  • math.degrees(a) returns angle a converted from radians to degrees;
  • math.radians(a) returns angle a converted from degrees to radians.
import math

deg = 60.0
x = math.radians(deg)  # 1.047...

cos = math.cos(x)  # 0.500...
sin = math.sin(x)  # 0.866...

degrees = math.degrees(x)  # 59.999...

As you can see, due to a limited precision of floats the value of degrees is actually 59.99999999999999 instead of expected 60.0.

It is impossible to cover all the math module in this topic so you can learn more from its documentation.

§3. The volume of a cylinder

Let's assume we have a cylinder with the height h = 5 and the radius r = 3. The formula for the volume of a cylinder is V = pi * (r)^2 * h. This is how we can calculate the volume using Python:

import math

h = 5
r = 3

volume = math.pi * math.pow(r, 2) * h  # 141.3716...

print(round(volume, 1))  # 141.4

In the code above, we used the round function to get a prettier value for printing.

As you can see, it is possible to round a number or find a maximum value in Python using just built-in functions. However, now you can use functions from the math module for more advanced tasks.


Up!

Random module

Sometimes it happens that we lack data and need to make up a bunch of new examples rather quickly. Of course, you can spend some time writing those examples yourself, but it's not so efficient, right? It would make more sense to shift the responsibility to your computer, namely, the Python's built-in module random.
In this module, a random search is used to generate elements and is performed using an algorithm whose starting point is a seed. Therefore, the results given aren't random at all and, technically, this module should have been called pseudo-random. Nevertheless, it may be useful for a large number of applications, such as modeling and simulation.

§1. Random method: first steps

First of all, we need to import the module:

import random

After we've managed to do the previous task, it's possible to try random.random()function that will provide us with a pseudo-random number from 0 to 1:

print(random.random())  # 0.5557276751294531

We can also control the pseudo-random behavior by specifying the seed manually, i.e. configure the new sequence of pseudo-random numbers using random.seed(x) function. You can set your own number or omit the optional argument x and consequently current system time would be used by default.

random.seed()
print(random.random())  # 0.956177930864557

Now try to set the x argument. Haven't you noticed the change of the result? If you choose 5, you'll get 0.6229016948897019 as a result, if 20 – 0.9056396761745207, etc. Thus, the seed controls the behavior of pseudo-random in Python and can be used with any other function of the random module.

§2. Random basic functions

Moving forward, other useful functions are:

  • random.uniform(a, b) – returns a pseudo-random float number in the range between a and b:
print(random.uniform(3, 100))  # 35.94079523197162
  • random.randint(a, b) – returns a pseudo-random integer number in the range between a and b:
print(random.randint(35, 53))  # 52
  • random.choice(seq)– returns a pseudo-random element from non-empty sequences:
print(random.choice('Voldemort'))  # m
  • random.randrange(a, b, c) – returns a pseudo-random number from a range between a and b with a step c. Just like with the range() function, the start and step arguments may be omitted with the default values 0 and 1 respectively. It means that the function can take one, two, or three parameters:
print(random.randrange(3, 100, 5))  # 18
print(random.randrange(1, 5))       # 2
print(random.randrange(100))        # 44
  • random.shuffle(seq, [random]) – shuffles a sequence. Attention: it doesn't work with immutable datatypes!
tiny_list = ['a', 'apple', 'b', 'banana', 'c', 'cat']
random.shuffle(tiny_list)
print(tiny_list)  # ['apple', 'banana', 'a', 'cat', 'b', 'c']
  • random.sample(population, k)– returns a pseudo-random k length list from a population sequence. This function is used for random sampling without replacement:
print(random.sample(range(100), 3))  # [24, 33, 91]

Furthermore, there are plenty of other functions that are used in common mathematical practice, e.g. random.gammavariate(alpha, beta) that is used for gamma distribution or random.gauss(mu, sigma) that returns Gaussian distribution. If you need such narrow-specialized function, you can address the Python documentation.

The pseudo-random generators of the random module should NOT be used for security purposes. If you are intending to work with passwords, security tokens and other sensitive data, check out the secrets module. It's considered more reliable since it generates secure random numbers.


Everybody wants to speak like master Yoda sometimes. Let's try to implement a program that will help us with it.
First, we turn the string of words into a list using the string.split() method.
Then use the function random.seed(43) and rearrange the obtained sequence.
To turn the list back into a string, use ' '.join(list).
Print the message in the end.
Note: you have to use random.seed(43) in this task!

Sample Input 1:

Luke, I'm your father

Sample Output 1:

your father I'm Luke,

Sample Input 2:

I will be back

Sample Output 2:

be back will I



Up!

Report Page