Thursday, May 29, 2014

Python module structure example

Python module structure example

Here is the directory tree:
directory tree of the example module
Double click to toggle code
checkbed
├── __init__.py
├── test1.py
└── test2.py

1 directory, 6 files

__init__.py is just an empty files that tells python that this folder can be used as a module. The content of the rest 2 files are listed here:

test1.py
Double click to toggle code
import os
from .test2 import sayhi

class sysutil():
    @staticmethod
    def modpath():
        return os.path.dirname(os.path.realpath(__file__))
    @staticmethod
    def cwd():
        return os.getcwd()
    @staticmethod
    def newsayhi():
        print("Indeed:")
        sayhi()
test2.py
Double click to toggle code
def sayhi():
    print("I said hi.")

Notice how test1.py imports a function from test2.py, by putting a dot before (meaning the current directory), this is called intra-package reference.

0 comments: