Tutorial 02

Creating an User-Defined Python Package

  1. Create a top level folder (e.g.: ws ) with the following sub-directory structure

     tutorials
         t02
             calculator
                 calculator_package
    

  1. Open a console/terminal within the calculator directory, activate the conda enviroment and start VS Code from the command line:

conda activate pta
code .

  1. Using VS Code create the following files under their respective directories

    ./calculate.py

    ./calculator_package/__init__.py

    ./calculator_package/calculator.py


  1. In the calculator.py create a Calculator Python class:

class Calculator:

    def get_version():
        return "1.0.0"

    def sum(self, val1, val2):
        """ Sum of 2 values """
        pass

    def sub(self, val1, val2):
        """ Subtract of 2 values """
        pass

    def mul(self, val1, val2):
        """ Multiply of 2 values """
        pass

    def div(self, val1, val2):
        """ Divide of 2 values """
        pass

    def exp(self, val1):
        """ Return e raised to the power x """
        pass

    def sqr(self, val1):
        """ Square root of a number """
        pass

    def ln(self, val1):
        """ Natural log of a number """
        pass

  1. Content of __init__.py:

__version__ = "1.0.0"

  1. Content of calculate.py:

from calculator_package.calculator import Calculator

if __name__ == '__main__':
    try:
        calculator = Calculator()
        print(calculator.get_version())  ## it will fail, find out why
    except Exception as e:
        print(e)

  1. In VS Code have as active open file calculate.py and from the Run menu select Start Debugging to run the Python code.


  1. Fix any issues and implement the Calculator functionality


  1. Run calculate.py form the command line:

python calculate.py
  1. Run calculator.py form the command line within the calculator directory:

python calculator_package/calculator.py