Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a sub-module in Python?

Tags:

python

module

Python has a module named "os". It also has some other module named "os.path" which is categorized under the "os".

I can use "os.path" methods even if only import the "os" module.

import os

print(os.path.join("sdfs","x"))

I wonder how can I define a sub-module like this?

like image 237
amone Avatar asked Mar 08 '23 21:03

amone


1 Answers

That's the __init__.py 'magic' of the os module - it imports its submodule path to its namespace, essentially giving you a way to access the latter even if you only import os.

os
|- path
   |- __init.__.py    # 2
|- __init__.py        # 1

The first __init__.py (#1) essentially has import .path so whenever you import just os, it imports path in its namespace, and therefore you can access it as os.path.

(NOTE: This is not exactly the case with the os module, but that's how to essentially achieve it)

like image 166
zwer Avatar answered Mar 16 '23 11:03

zwer