Python Language Importing modules Importing specific names from a module

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Instead of importing the complete module you can import only specified names:

from random import randint # Syntax "from MODULENAME import NAME1[, NAME2[, ...]]"
print(randint(1, 10))      # Out: 5

from random is needed, because the python interpreter has to know from which resource it should import a function or class and import randint specifies the function or class itself.

Another example below (similar to the one above):

from math import pi
print(pi)                  # Out: 3.14159265359

The following example will raise an error, because we haven't imported a module:

random.randrange(1, 10)    # works only if "import random" has been run before

Outputs:

NameError: name 'random' is not defined

The python interpreter does not understand what you mean with random. It needs to be declared by adding import random to the example:

import random
random.randrange(1, 10)


Got any Python Language Question?