Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Top Posters

Who's Online (1)

Powered by Vanilla. Made with Bootstrap.
Creating your own modules
  • A module is a python file containing definitions and statements. For example, when you import the math module, you can access math module functions such as math.pi(). Well in this short but informative guide I'll teach you how to build your own basic modules and import them into your Python code. But first, a quick lesson on Python path's. When you import a module python looks in a set of directories. This can be found in the PYTHONPATH system variable. When you import a module python looks in these places:
    The current directory
    Directories in the PYTHONPATH variable
    The default search path

    So in this guide I'll be showing you how to create your own module in the same directory as the python file and import it into your code(and of course use it)

    [--Creating the module--]
    A module usually starts with .py, but of course you can import extended modules written in C, C++ etc. I will not be going over that in this guide. So first things first open a new python file. I'll be calling it mymodule.py
    This is what mymodule.py looks like

    def myfunction()
    print(\"Hi\n\")

    Very simple. Just one function that prints the word Hi. Now we create a new python script(In the same directory) and import the module.

    import mymodule
    mymodule.myfunction()

    And this will call the myfunction() from mymodule. If you run this it prints Hi. Now lets try passing arguments. Modify the mymodule.py so it looks like this:

    def myfunction(arg):
    print(arg)

    Also simple. We are creating myfunction with one argument(arg). Then we are printing the argument. Now for the python script:

    import mymodule
    mymodule.myfunction(\"test\")

    Save it and run it. You should get the output, "test". You can pass multiple arguments into myfunction(). For example lets take a look at this edited mymodule that multiplies two arguments.

    def myfunction(x, y):
    print(x * y)

    And the script:

    import mymodule

    x = 2
    y = 3
    mymodule.myfunction(x, y)

    This is setting x to 2 and y to 3. Then we are calling mymodule's function, myfunction. We are passing two arguments to it(x and y). In mymodule, we multiply the two arguments passed to myfunction. So in the python script we should get the correct answer.

    Well I hope I taught you a little something about creating simple modules and importing them into your code.

    --chroniccommand