Python modules and packages

Any Python source file can be used as a module, and any functions and classes you define in that source file can be reused. To load the code, the file referencing the module needs to use the import keyword. Three things happen when the file is imported:

  1. The file creates a new namespace for the objects defined in the source file
  2. The caller executes all the code contained in the module
  3. The file creates a name within the caller that refers to the module being imported. The name matches the name of the module

Remember the subtract() function that you defined using the interactive shell? To reuse the function, we can put it into a file named subtract.py:

def subtract(a, b):  c = a - b  return c

In a file within the ...

Get Mastering Python Networking - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.