Knowledgebase

Modules and Importing Code Print

  • python, guide, howto, solution, zillionkinghost, hosting, support
  • 0

Using code from elsewhere.

WHAT A MODULE IS

A Python file whose contents can be used from another file.

WHAT A PACKAGE IS

A collection of modules.

HOW TO USE ONE

Import it, then refer to what it contains.

WHAT COMES WITH PYTHON

An extensive standard library: files, dates, JSON, regular expressions, networking, and much more.

WHY THAT MATTERS

Before installing anything, check whether the standard library already does it.

Frequently it does.

HOW TO IMPORT

Import the whole module, or specific names from it.

WHAT TO PREFER

Importing the module and referring to its contents explicitly.

It makes the origin of each name obvious.

WHAT TO AVOID

Importing everything from a module, which pollutes your namespace and obscures where names came from Circular imports, where two modules import each other

WHERE PYTHON LOOKS

In the current directory, then in installed locations.

WHAT THAT CAUSES

A file named the same as a library shadows it.

Avoid naming your files after common libraries.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot