Saturday, July 2, 2022

Python - Modules

Modules are like libraries.

They let you tap into other people's code and packages.

For example, say there is a file named "mymodule.py" with these contents (between the dashed lines):

---------

def greeting(name):
    print("Hello, " + name)

---------

We would then access the module with the code below:

import mymodule

# Hello, John
mymodule.greeting("John")


Here is how to access variables stored in a module:

Filename: mymodule.py:

--------- 

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}


---------

How I would use it:

import mymodule

a = mymodule.person1["age"]
 

#36
print(a)

There are built-in modules.  For example, platform

We can display a list of functions in a module like this:

import platform

x = dir(platform)
print(x)