MODULES IN PYTHON


In this article, we will learn about creating and importing self created modules in Python. We will explore different ways of exporting python modules as well and learn how to use the built-in modules in python.





What are Modules in Python?

A module is a python file with a ‘.py’ extension which consists of functions, statements and variables. The reason we use modules is to break down big programs into simpler and smaller ones. We can reuse module files anytime as well.

Modules in Python

Let’s create a module file and name it as ‘my_code.py’, and create a function inside it.

def my_function(): 
    print("This is a module file") 
my_function()

Importing a Module

Now that we created a module file, let’s save it in the same directory where our main python file is stored. Now let’s suppose we are inside our main.py file; now it’s time to use the import statement to import the my_code.py file:

import my_code 

my_code.my_function()

When the python interpreter sees an import statement, it imports the module file if the module is present in the same directory, otherwsie it will show an error. Once the module is imported then you can call the relevant function name that you want to use.

my_code.my_function()

Note: Whenever you want to use the function from your module file, then you have to follow the syntax: modulename.functionname().





‘From’ in Import Statement

Sometimes the module file is gonna have more than one block of code so Python lets you import a specific block from your module, let’s say that you have a file named info_modules.py and it has two dictionaries named ‘person_1’ and ‘person_2’ and you want to import ‘person_1’ in your main program.

person_1 = { 'name': "hira", 'age': '29', 'gender': 'Female', } 

person_2 = { 'name': "Smith", 'age': '29', 'gender': 'Male', }

Importing person_1 in the main.py file using from statement

from my_code import person_1 
print(person_1)

Output will be:

{'name': 'hira', 'age': '29', 'gender': 'Female'}




Note: once you  have specifically imported the function, variable or statement in your main program then you don’t have use modulename.functionname() syntax while calling it in your main file. Just call the name directly with from statement.


Renaming a Module using Alias

You can rename a module as well in python. Let’s say you want to call your info_modules as info as a short form so that you can have flexibility, for example:

import info_modules as info 
print(info.person_1)

Output will be:

{'name': 'hira', 'age': '29', 'gender': 'Female'}

Built in Modules

There is an extensive list of all the built-in modules that python supports, each caters a different functionality and usage depending on what we want to calculate. In order to see the list of modules python supports just type:

print(help('modules'))

Output will be:

IPython             _weakrefset         heapq               secrets
__future__          _winapi             hmac                select
_abc                abc                 html                selectors
_ast                aifc                http                setuptools
_asyncio            antigravity         idlelib             shelve
_bisect             argparse            imaplib             shlex
_blake2             array               imghdr              shutil
_bootlocale         ast                 imp                 signal
_bz2                asynchat            importlib           simplegeneric
_codecs             asyncio             ind                 site
_codecs_cn          asyncore            inspect             six
_codecs_hk          atexit              io                  smtpd
_codecs_iso2022     audioop             ipaddress           smtplib
_codecs_jp          autoreload          ipython_genutils    sndhdr
_codecs_kr          backcall            itertools           socket
_codecs_tw          base64              jedi                socketserver
_collections        bdb                 json                sqlite3
_collections_abc    binascii            keyword             sre_compile
_compat_pickle      binhex              lib2to3             sre_constants
_compression        bisect              linecache           sre_parse
_contextvars        builtins            locale              ssl
_csv                bz2                 logging             stat
_ctypes             cProfile            lzma                statistics
_ctypes_test        calendar            macpath             storemagic
_datetime           cgi                 mailbox             string
_decimal            cgitb               mailcap             stringprep
_distutils_findvs   chunk               marshal             struct
_dummy_thread       cmath               math                subprocess
_elementtree        cmd                 mimetypes           sunau
_functools          code                mmap                symbol
_hashlib            codecs              modulefinder        sympyprinting
_heapq              codeop              msilib              symtable
_imp                collections         msvcrt              sys
_io                 colorama            multiprocessing     sysconfig
_json               colorsys            netrc               tabnanny
_locale             compileall          nntplib             tarfile
_lsprof             concurrent          nt                  telnetlib
_lzma               configparser        ntpath              tempfile
_markupbase         contextlib          nturl2path          test
_md5                contextvars         numbers             tests
_msi                copy                opcode              textwrap
_multibytecodec     copyreg             operator            this
_multiprocessing    crypt               optparse            threading
_opcode             csv                 os                  time
_operator           ctypes              parser              timeit
_osx_support        curses              parso               tkinter
_overlapped         cythonmagic         pathlib             token
_pickle             dataclasses         pdb                 tokenize
_py_abc             datetime            pickle              trace
_pydecimal          dbm                 pickleshare         traceback
_pyio               decimal             pickletools         tracemalloc
_queue              decorator           pip                 traitlets
_random             difflib             pipes               tty
_sha1               dis                 pkg_resources       turtle
_sha256             distutils           pkgutil             turtledemo
_sha3               doctest             platform            types
_sha512             dummy_threading     plistlib            typing
_signal             easy_install        poplib              unicodedata
_sitebuiltins       email               posixpath           unittest
_socket             encodings           pprint              urllib
_sqlite3            ensurepip           profile             uu
_sre                enum                prompt_toolkit      uuid
_ssl                errno               pstats              venv
_stat               faulthandler        pty                 warnings
_string             filecmp             py_compile          wave
_strptime           fileinput           pyclbr              wcwidth
_struct             fnmatch             pydoc               weakref
_symtable           formatter           pydoc_data          webbrowser
_testbuffer         fractions           pyexpat             winreg
_testcapi           ftplib              pygments            winsound
_testconsole        functools           queue               wsgiref
_testimportmultiple gc                  quopri              xdrlib
_testmultiphase     genericpath         random              xml
_thread             getopt              re                  xmlrpc
_threading_local    getpass             reprlib             xxsubtype
_tkinter            gettext             rlcompleter         zipapp
_tracemalloc        glob                rmagic              zipfile
_warnings           gzip                runpy               zipimport
_weakref            hashlib             sched               zlib