Python Modules with Submodules and Functions

I have a question about how numpy type libraries work. When I import numpy, I have access to many built-in classes, functions and constants such as numpy.array, numpy.sqrt, etc.

But inside numpy there are additional submodules like numpy.testing.

How it's done? In my limited experience, modules with submodules are just folders with the init .py file, and modules with functions / classes are the actual python files. How to create a folder module that also has functions / classes?

+7
function python module
source share
1 answer

The folder with the .py and a __init__.py files is called package . One of these files containing classes and functions is module . Nesting folders can give you subpackages.

So, for example, if I had the following structure:

  mypackage __init__.py module_a.py module_b.py mysubpackage __init__.py module_c.py module_d.py 

I could import mypackage.module_a or mypackage.mysubpacakge.module_c etc.

You can also add mypackage functions (e.g. numpy functions mentioned) by putting this code in __init__.py . Although it is usually considered ugly.

If you look at numpy __init__.py , you will see a lot of code there - many of them define these classes and top-level functions. The __init__.py code is the first thing that executes when a package is downloaded.

+17
source share

All Articles