liveBook · Manning

Import statement

As explained in Get Programming: Learn to code with Python

An import statement is a source-code declaration that makes names or definitions from another module, package, or namespace available in the current scope.

An import statement brings definitions from another file or library into your program, so you can use existing classes and functions instead of copying their definitions. Imports also help keep code organized. section 35.1

Importing classes from another file

If shapes.py defines Circle and Rectangle, write `import shapes` in another file in the same folder. You can then create objects from those classes. The import line uses the filename without its .py extension. section 35.1

Imports can also make library features available. For example, after `import random`, you can use random.random() for a value from 0 up to, but not including, 1; random.randint(a, b) for an integer from a through b; or random.choice(L) for an element from list L. section 34.1

import shapes

See the import line used to access classes defined in shapes.py. section 35.1

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines importing and explains module names, same-folder files, and library types through examples.
Examples
Uses Circle and Rectangle classes from shapes.py and random functions for numbers and list selection.
What you can do after
Apply imports to use classes from another file and random operations from a library.
How it connects
Connects imports to modules, libraries, classes, objects, methods, and code organization.

Also explained in

Compare how 13 books explain import statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.