Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python modules with submodules and functions

I had a question on how libraries like numpy work. When I import numpy, I'm given access to a host of built in classes, functions, and constants such as numpy.array, numpy.sqrt etc.

But within numpy there are additional submodules such as numpy.testing.

How is this done? In my limited experience, modules with submodules are simply folders with a __init__.py file, while modules with functions/classes are actual python files. How does one create a module "folder" that also has functions/classes?

like image 854
ImpGuard Avatar asked Sep 01 '13 04:09

ImpGuard


People also ask

What are submodules in Python?

In my limited experience, modules with submodules are simply folders with a __init__.py file, while modules with functions/classes are actual python files.

What are modules and functions in Python?

A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.

What are modules and submodules?

Modules are the foundational building blocks of your course. They can be organized by date, theme, topic, learning outcome, etc. Submodules are nested within modules and generally include more specific details and information.

What are the different types of modules in Python?

Modules in Python can be of two types: Built-in Modules. User-defined Modules.


1 Answers

A folder with .py files and a __init__.py is called a package. One of those files containing classes and functions is a module. Folder nesting 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.mysubpackage.module_c and so on.

You could also add functions to mypackage (like the numpy functions you mentioned) by placing that code in the __init__.py. Though this is usually considered to be ugly.

If you look at numpy's __init__.py you will see a lot of code in there - a lot of this is defining these top-level classes and functions. The __init__.py code is the first thing executed when the package is loaded.

like image 68
Mike Vella Avatar answered Sep 17 '22 17:09

Mike Vella