Sunday, April 20, 2025

Python Modules

Modules are external files that hold additional source (functions) that we can use - if we need them.

Create file "external.py" - that will be our module with one function my_func(), for now:


def my_func():
    print("I am from external world...")

This is our main file where we are practicing: "playground.py". First we need to "import" external module (without extension ".py").

Then, just call our function from module, with dot in the middle:


import external

external.my_func()

Result: 


I am from external world...
>>> 

Functions in main file are also fine:


import external

external.my_func()

def localone():
    print("Local Stuff...")

localone()

Result: 


I am from external world...
Local Stuff...
>>> 

Create new module "anotherone.py" with this source:


print("AUTOMATIC print on module import")

Import "anotherone.py" into our main script:


import external, anotherone

external.my_func()

def localone():
    print("Local Stuff...")

localone()

Stuff from "anotherone.py" will be immediately executed when we run our mains script.

This can be security problem if you just like to grab things from Internet, without checking:


AUTOMATIC print on module import
I am from external world...
Local Stuff...
>>> 

We can use short names for modules:


import external as ex

ex.my_func()

Or we can grab everything from module in such a way that there's no need to type module name every time when we need specific function from that module:


from external import *

my_func()

Result: 


I am from external world...
>>> 

Next tutorial will be dedicated to practical example how to use modules from Standard Library.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...