In scopul organizarii logice a codului, limbajul Python permite includerea codurilor sursa care deservesc un scop comun, in module, care pot fi considerate librarii de componente software. In limbajul Python un modul reprezinta un fisier Python, care contine cod scris in limbaj Python. Un modul poate contine urmatoarele tipuri de informatii:

- docstring: descrie scopul/continutul modulului
- variabile
- functii
- clase
- cod executabil

Numele fisierului care reprezinta un modul Python este numele modulului cu extensia .py. De exemplu math.py este un modul furnizat implicit la instalarea mediului Python, care contine functii matematice diverse.

Lista modulelor instalate la instalarea platformei Anaconda se poate obtine cu comanda:

In [1]:

    help('modules')

    Please wait a moment while I gather a list of all available modules...

    C:\Users\user\anaconda3\lib\site-packages\IPython\kernel\__init__.py:13: ShimWarning: The `IPython.kernel` package has been deprecated since IPython 4.0.You should import from ipykernel or jupyter_client instead.
      "You should import from ipykernel or jupyter_client instead.", ShimWarning)
    distributed.dashboard.proxy - INFO - To route to workers diagnostics web server please install jupyter-server-proxy: python -m pip install jupyter-server-proxy
    C:\Users\user\anaconda3\lib\site-packages\nltk\twitter\__init__.py:22: UserWarning: The twython library has not been installed. Some functionality from the twitter package will not be available.
      "The twython library has not been installed. "
    C:\Users\user\anaconda3\lib\site-packages\skimage\viewer\utils\__init__.py:1: UserWarning: Recommended matplotlib backend is `Agg` for full skimage.viewer functionality.
      from .core import *
    C:\Users\user\anaconda3\lib\site-packages\sklearn\externals\joblib\__init__.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
      warnings.warn(msg, category=FutureWarning)
    C:\Users\user\anaconda3\lib\site-packages\qtawesome\iconic_font.py:312: UserWarning: You need to have a running QApplication to use QtAwesome!
      warnings.warn("You need to have a running "
    C:\Users\user\anaconda3\lib\pkgutil.py:107: VisibleDeprecationWarning: zmq.eventloop.minitornado is deprecated in pyzmq 14.0 and will be removed.
        Install tornado itself to use zmq with the tornado IOLoop.

      yield from walk_packages(path, info.name+'.', onerror)

    Crypto              brain_subprocess    math                smtpd
    Cython              brain_threading     matplotlib          smtplib
    IPython             brain_typing        mccabe              sndhdr
    OpenSSL             brain_uuid          menuinst            snowballstemmer
    PIL                 bs4                 mimetypes           socket
    PyQt5               builtins            mistune             socketserver
    __future__          bz2                 mkl                 socks
    _abc                cProfile            mkl_fft             sockshandler
    _ast                calendar            mkl_random          sortedcollections
    _asyncio            cats                mmap                sortedcontainers
    _bisect             certifi             mmapfile            soupsieve
    _blake2             cffi                mmsystem            sphinx
    _bootlocale         cgi                 mock                sphinxcontrib
    _bz2                cgitb               modul1              spyder
    _cffi_backend       chardet             modulefinder        spyder_kernels
    _codecs             chunk               more_itertools      sqlalchemy
    _codecs_cn          click               mpmath              sqlite3
    _codecs_hk          cloudpickle         msgpack             sre_compile
    _codecs_iso2022     clyent              msilib              sre_constants
    _codecs_jp          cmath               msvcrt              sre_parse
    _codecs_kr          cmd                 multipledispatch    ssl
    _codecs_tw          code                multiprocessing     sspi
    _collections        codecs              nacl                sspicon
    _collections_abc    codeop              navigator_updater   stat
    _compat_pickle      collections         nbconvert           statistics
    _compression        colorama            nbformat            statsmodels
    _contextvars        colorsys            netbios             storemagic
    _csv                commctrl            netrc               string
    _ctypes             compileall          networkx            stringprep
    _ctypes_test        comtypes            nltk                struct
    _datetime           concurrent          nntplib             subprocess
    _decimal            conda               nose                sunau
    _dummy_thread       conda_build         notebook            symbol
    _elementtree        conda_env           nt                  sympy
    _functools          conda_package_handling ntpath              sympyprinting
    _hashlib            conda_verify        ntsecuritycon       symtable
    _heapq              configparser        nturl2path          sys
    _imp                contextlib          numba               sysconfig
    _io                 contextlib2         numbers             tables
    _json               contextvars         numexpr             tabnanny
    _locale             copy                numpy               tarfile
    _lsprof             copyreg             numpydoc            tblib
    _lzma               crypt               odbc                telnetlib
    _markupbase         cryptography        olefile             tempfile
    _md5                csv                 opcode              terminado
    _msi                ctypes              openpyxl            test
    _multibytecodec     curl                operator            test_data
    _multiprocessing    curses              optparse            test_pycosat
    _nsis               cwp                 os                  testpath
    _opcode             cycler              packaging           tests
    _operator           cython              pandas              textwrap
    _osx_support        cythonmagic         pandocfilters       this
    _overlapped         cytoolz             paramiko            threading
    _pickle             dask                parser              time
    _py_abc             dataclasses         parso               timeit
    _pydecimal          datetime            partd               timer
    _pyio               dateutil            past                tkinter
    _pylief             dbi                 path                tlz
    _pyrsistent_version dbm                 pathlib             token
    _pytest             dde                 pathlib2            tokenize
    _queue              decimal             pathtools           toolz
    _random             decorator           patsy               tornado
    _sha1               defusedxml          pdb                 tqdm
    _sha256             diff_match_patch    pep8                trace
    _sha3               difflib             perfmon             traceback
    _sha512             dis                 pexpect             tracemalloc
    _signal             distributed         pickle              traitlets
    _sitebuiltins       distutils           pickleshare         tty
    _socket             doctest             pickletools         turtle
    _sqlite3            docutils            pip                 turtledemo
    _sre                dummy_threading     pipes               types
    _ssl                easy_install        pkg_resources       typing
    _stat               email               pkginfo             ujson
    _string             encodings           pkgutil             unicodecsv
    _strptime           ensurepip           platform            unicodedata
    _struct             entrypoints         plistlib            unittest
    _symtable           enum                pluggy              urllib
    _system_path        errno               ply                 urllib3
    _testbuffer         et_xmlfile          poplib              uu
    _testcapi           fastcache           posixpath           uuid
    _testconsole        faulthandler        pprint              venv
    _testimportmultiple filecmp             profile             warnings
    _testmultiphase     fileinput           prometheus_client   watchdog
    _thread             filelock            prompt_toolkit      wave
    _threading_local    flake8              pstats              wcwidth
    _tkinter            flask               psutil              weakref
    _tracemalloc        fnmatch             pty                 webbrowser
    _warnings           formatter           pvectorc            webencodings
    _weakref            fractions           py                  werkzeug
    _weakrefset         fsspec              py_compile          wheel
    _win32sysloader     ftplib              pyclbr              widgetsnbextension
    _winapi             functools           pycodestyle         win2kras
    _winxptheme         future              pycosat             win32api
    _yaml               gc                  pycparser           win32clipboard
    abc                 genericpath         pycurl              win32com
    adodbapi            getopt              pydoc               win32con
    afxres              getpass             pydoc_data          win32console
    aifc                gettext             pydocstyle          win32cred
    alabaster           gevent              pyexpat             win32crypt
    anaconda_navigator  glob                pyflakes            win32cryptcon
    anaconda_project    glob2               pygments            win32ctypes
    antigravity         greenlet            pylab               win32event
    argh                gzip                pylint              win32evtlog
    argparse            h5py                pyls                win32evtlogutil
    array               hashlib             pyls_jsonrpc        win32file
    asn1crypto          heapdict            pyodbc              win32gui
    ast                 heapq               pyparsing           win32gui_struct
    astroid             hmac                pyreadline          win32help
    astropy             html                pyrsistent          win32inet
    asynchat            html5lib            pytest              win32inetcon
    asyncio             http                pytest_arraydiff    win32job
    asyncore            hypothesis          pytest_astropy_header win32lz
    atexit              idlelib             pytest_doctestplus  win32net
    atomicwrites        idna                pytest_openfiles    win32netcon
    attr                imageio             pytest_remotedata   win32pdh
    audioop             imagesize           pythoncom           win32pdhquery
    autopep8            imaplib             pytz                win32pdhutil
    autoreload          imghdr              pywin               win32pipe
    babel               imp                 pywin32_bootstrap   win32print
    backcall            importlib           pywin32_testutil    win32process
    backports           importlib_metadata  pywintypes          win32profile
    base64              inspect             pywt                win32ras
    bcrypt              intervaltree        pyximport           win32rcparser
    bdb                 io                  qdarkstyle          win32security
    binascii            ipaddress           qtawesome           win32service
    binhex              ipykernel           qtconsole           win32serviceutil
    binstar_client      ipykernel_launcher  qtpy                win32timezone
    bisect              ipython_genutils    queue               win32trace
    bitarray            ipywidgets          quopri              win32traceutil
    bkcharts            isapi               random              win32transaction
    bleach              isort               rasutil             win32ts
    bokeh               isympy              re                  win32ui
    boto                itertools           readline            win32uiole
    bottleneck          itsdangerous        regcheck            win32verstamp
    brain_argparse      jdcal               regutil             win32wnet
    brain_attrs         jedi                reprlib             win_inet_pton
    brain_builtin_inference jinja2              requests            win_unicode_console
    brain_collections   joblib              rlcompleter         wincertstore
    brain_crypt         json                rmagic              winerror
    brain_curses        json5               rope                winioctlcon
    brain_dataclasses   jsonschema          rtree               winnt
    brain_dateutil      jupyter             ruamel_yaml         winperf
    brain_fstrings      jupyter_client      run                 winpty
    brain_functools     jupyter_console     runpy               winreg
    brain_gi            jupyter_core        sched               winsound
    brain_hashlib       jupyterlab          scipy               winxpgui
    brain_http          jupyterlab_server   scripts             winxptheme
    brain_io            keyring             seaborn             wrapt
    brain_mechanize     keyword             secrets             wsgiref
    brain_multiprocessing kiwisolver          select              xdrlib
    brain_namedtuple_enum lazy_object_proxy   selectors           xlrd
    brain_nose          lib2to3             send2trash          xlsxwriter
    brain_numpy_core_fromnumeric libarchive          servicemanager      xlwings
    brain_numpy_core_function_base libfuturize         setuptools          xlwt
    brain_numpy_core_multiarray libpasteurize       shelve              xml
    brain_numpy_core_numeric lief                shlex               xmlrpc
    brain_numpy_core_numerictypes linecache           shutil              xmltodict
    brain_numpy_core_umath llvmlite            signal              xxsubtype
    brain_numpy_ndarray locale              simplegeneric       yaml
    brain_numpy_random_mtrand locket              singledispatch      yapf
    brain_numpy_utils   logging             singledispatch_helpers yapftests
    brain_pkg_resources lxml                sip                 zict
    brain_pytest        lzma                sipconfig           zipapp
    brain_qt            macpath             sipdistutils        zipfile
    brain_random        mailbox             site                zipimport
    brain_re            mailcap             six                 zipp
    brain_six           markupsafe          skimage             zlib
    brain_ssl           marshal             sklearn             zmq

    Enter any module name to get more help.  Or, type "modules spam" to search
    for modules whose name or summary contain the string "spam".

iar documentatia completa a modulelor respective se poate accesa la adresa: https://docs.python.org/3/py-modindex.html. In cazul in care se doreste obtinerea unor informatii despre un modul anume, se executa comanda

    help('nume_modul')

In [2]:

    import math
    help('math')

    Help on built-in module math:

    NAME
        math

    DESCRIPTION
        This module provides access to the mathematical functions
        defined by the C standard.

    FUNCTIONS
        acos(x, /)
            Return the arc cosine (measured in radians) of x.

        acosh(x, /)
            Return the inverse hyperbolic cosine of x.

        asin(x, /)
            Return the arc sine (measured in radians) of x.

        asinh(x, /)
            Return the inverse hyperbolic sine of x.

        atan(x, /)
            Return the arc tangent (measured in radians) of x.

        atan2(y, x, /)
            Return the arc tangent (measured in radians) of y/x.

            Unlike atan(y/x), the signs of both x and y are considered.

        atanh(x, /)
            Return the inverse hyperbolic tangent of x.

        ceil(x, /)
            Return the ceiling of x as an Integral.

            This is the smallest integer >= x.

        copysign(x, y, /)
            Return a float with the magnitude (absolute value) of x but the sign of y.

            On platforms that support signed zeros, copysign(1.0, -0.0)
            returns -1.0.

        cos(x, /)
            Return the cosine of x (measured in radians).

        cosh(x, /)
            Return the hyperbolic cosine of x.

        degrees(x, /)
            Convert angle x from radians to degrees.

        erf(x, /)
            Error function at x.

        erfc(x, /)
            Complementary error function at x.

        exp(x, /)
            Return e raised to the power of x.

        expm1(x, /)
            Return exp(x)-1.

            This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.

        fabs(x, /)
            Return the absolute value of the float x.

        factorial(x, /)
            Find x!.

            Raise a ValueError if x is negative or non-integral.

        floor(x, /)
            Return the floor of x as an Integral.

            This is the largest integer <= x.

        fmod(x, y, /)
            Return fmod(x, y), according to platform C.

            x % y may differ.

        frexp(x, /)
            Return the mantissa and exponent of x, as pair (m, e).

            m is a float and e is an int, such that x = m * 2.**e.
            If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.

        fsum(seq, /)
            Return an accurate floating point sum of values in the iterable seq.

            Assumes IEEE-754 floating point arithmetic.

        gamma(x, /)
            Gamma function at x.

        gcd(x, y, /)
            greatest common divisor of x and y

        hypot(x, y, /)
            Return the Euclidean distance, sqrt(x*x + y*y).

        isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
            Determine whether two floating point numbers are close in value.

              rel_tol
                maximum difference for being considered "close", relative to the
                magnitude of the input values
              abs_tol
                maximum difference for being considered "close", regardless of the
                magnitude of the input values

            Return True if a is close in value to b, and False otherwise.

            For the values to be considered close, the difference between them
            must be smaller than at least one of the tolerances.

            -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
            is, NaN is not close to anything, even itself.  inf and -inf are
            only close to themselves.

        isfinite(x, /)
            Return True if x is neither an infinity nor a NaN, and False otherwise.

        isinf(x, /)
            Return True if x is a positive or negative infinity, and False otherwise.

        isnan(x, /)
            Return True if x is a NaN (not a number), and False otherwise.

        ldexp(x, i, /)
            Return x * (2**i).

            This is essentially the inverse of frexp().

        lgamma(x, /)
            Natural logarithm of absolute value of Gamma function at x.

        log(...)
            log(x, [base=math.e])
            Return the logarithm of x to the given base.

            If the base not specified, returns the natural logarithm (base e) of x.

        log10(x, /)
            Return the base 10 logarithm of x.

        log1p(x, /)
            Return the natural logarithm of 1+x (base e).

            The result is computed in a way which is accurate for x near zero.

        log2(x, /)
            Return the base 2 logarithm of x.

        modf(x, /)
            Return the fractional and integer parts of x.

            Both results carry the sign of x and are floats.

        pow(x, y, /)
            Return x**y (x to the power of y).

        radians(x, /)
            Convert angle x from degrees to radians.

        remainder(x, y, /)
            Difference between x and the closest integer multiple of y.

            Return x - n*y where n*y is the closest integer multiple of y.
            In the case where x is exactly halfway between two multiples of
            y, the nearest even value of n is used. The result is always exact.

        sin(x, /)
            Return the sine of x (measured in radians).

        sinh(x, /)
            Return the hyperbolic sine of x.

        sqrt(x, /)
            Return the square root of x.

        tan(x, /)
            Return the tangent of x (measured in radians).

        tanh(x, /)
            Return the hyperbolic tangent of x.

        trunc(x, /)
            Truncates the Real x to the nearest Integral toward 0.

            Uses the __trunc__ magic method.

    DATA
        e = 2.718281828459045
        inf = inf
        nan = nan
        pi = 3.141592653589793
        tau = 6.283185307179586

    FILE
        (built-in)

O listare sumara a continutului unui modul se poate obtine apeland functia `dir()` furnizata de Python"

    dir('nume_modul')

In [3]:

    help(dir(math))

    Help on list object:

    class list(object)
     |  list(iterable=(), /)
     |
     |  Built-in mutable sequence.
     |
     |  If no argument is given, the constructor creates a new empty list.
     |  The argument must be an iterable if specified.
     |
     |  Methods defined here:
     |
     |  __add__(self, value, /)
     |      Return self+value.
     |
     |  __contains__(self, key, /)
     |      Return key in self.
     |
     |  __delitem__(self, key, /)
     |      Delete self[key].
     |
     |  __eq__(self, value, /)
     |      Return self==value.
     |
     |  __ge__(self, value, /)
     |      Return self>=value.
     |
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |
     |  __getitem__(...)
     |      x.__getitem__(y) <==> x[y]
     |
     |  __gt__(self, value, /)
     |      Return self>value.
     |
     |  __iadd__(self, value, /)
     |      Implement self+=value.
     |
     |  __imul__(self, value, /)
     |      Implement self*=value.
     |
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  __iter__(self, /)
     |      Implement iter(self).
     |
     |  __le__(self, value, /)
     |      Return self<=value.
     |
     |  __len__(self, /)
     |      Return len(self).
     |
     |  __lt__(self, value, /)
     |      Return self<value.
     |
     |  __mul__(self, value, /)
     |      Return self*value.
     |
     |  __ne__(self, value, /)
     |      Return self!=value.
     |
     |  __repr__(self, /)
     |      Return repr(self).
     |
     |  __reversed__(self, /)
     |      Return a reverse iterator over the list.
     |
     |  __rmul__(self, value, /)
     |      Return value*self.
     |
     |  __setitem__(self, key, value, /)
     |      Set self[key] to value.
     |
     |  __sizeof__(self, /)
     |      Return the size of the list in memory, in bytes.
     |
     |  append(self, object, /)
     |      Append object to the end of the list.
     |
     |  clear(self, /)
     |      Remove all items from list.
     |
     |  copy(self, /)
     |      Return a shallow copy of the list.
     |
     |  count(self, value, /)
     |      Return number of occurrences of value.
     |
     |  extend(self, iterable, /)
     |      Extend list by appending elements from the iterable.
     |
     |  index(self, value, start=0, stop=9223372036854775807, /)
     |      Return first index of value.
     |
     |      Raises ValueError if the value is not present.
     |
     |  insert(self, index, object, /)
     |      Insert object before index.
     |
     |  pop(self, index=-1, /)
     |      Remove and return item at index (default last).
     |
     |      Raises IndexError if list is empty or index is out of range.
     |
     |  remove(self, value, /)
     |      Remove first occurrence of value.
     |
     |      Raises ValueError if the value is not present.
     |
     |  reverse(self, /)
     |      Reverse *IN PLACE*.
     |
     |  sort(self, /, *, key=None, reverse=False)
     |      Stable sort *IN PLACE*.
     |
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |
     |  __hash__ = None

# 1. Crearea unui modul¶

Un modul Python se poate crea utilizand oricare editor de text, prin salvarea fisierului care contine codul Python cu extensia .py.

In [4]:

    # Exemplul 1 - crearea unui modul "cats"

    # urmatoarele linii se scriu in oricare editor de text
    # apoi se salveaza fisierul in directorul curent de lucru cu denumirea "cats.py"
    # numele modulului devine "cats"

    # documentare modul
    '''
        This module contains functions used to
        model the behaviour of cats.
    '''

    # variabile definite in modul
    cat_name = 'Gimi'
    cat_color = 'Black'
    cat_age  = 1

    # functii modul
    def set_name(name):
        global cat_name
        cat_name = name

    def get_name():
        global cat_name
        return cat_name

    def set_color(color):
        global cat_color
        cat_color = color

    def get_color():
        global cat_color
        return cat_color

    def set_age(age):
        global cat_age
        cat_age = age

    def get_age():
        global cat_age
        return cat_age

    def cat_talks():
        return 'Meow'

    def cat_eats():
        return "Niam, I'am hungry!"

    def cat_runs():
        return "I'm running faster than the wind!"

# 2. Importarea continutului unui modul¶

Intr-un cod, continutul unui modul devine accesibil numai daca acesta se importa in codul respectiv. Dupa importarea modulului, tot continutul sau devine vizibil codului in care a fost importat, incepand cu linia de cod in care s-a executat comanda de importare a modulului. Din acest motiv, se recomanda ca importarea modulelor necesare unui cod, sa fie realizata la inceputul acestuia.

Sintaxa:

    import nume_modul_1, ... , nume_modul_n

# 3. Accesarea continutului unui modul¶

Pentru accesarea membrilor (componentelor) unui modul, se utilizeaza operatorul punct `.`.

Sintaxa:

    nume_modul.nume_membru   # nume_membru poate fi oricare nume de functie sau variabila
                             # din continutul modulului importat

In [5]:

    # Exemplul 2 - accesarea membrilor unui modul

    import cats

    name  = cats.get_name()
    age   = cats.get_age()
    words = cats.cat_talks()

    print(  f'{name} has {age} years and says {words} to you' )

    cats.set_name('Sunny')
    cats.set_age(8)
    name  = cats.get_name()
    age   = cats.get_age()

    print(  f'{name} has {age} years and says {words} to you' )

    Gimi has 1 years and says Meow to you
    Sunny has 8 years and says Meow to you

# 4. Redenumirea printr-un alias a unui modul¶

Daca este convenabil, la importarea sa, un modul se poate redenumi utilizand `as`. Dupa redenumire continutul modulului se poate accesa prin aplicarea operatorului punct alias-ului.

Sintaxa:

    import nume_modul as alias

    alias.nume_membru

In [6]:

    # Exemplul 3 - redenumirea unui modul

    import cats as ct

    print(ct.cat_eats())
    print(ct.cat_runs())

    Niam niam!
    I'm running faster than wind!

# 5. Specificarea membrilor importati dintr-un modul¶

Prin comanda `import`, in fisierul curent se importa intregul continut al unui modul. In limbajul Python, se pot importa dintr-un modul numai membrii care sunt utilizati in cod, prin comanda `from`. Ulterior, membrii importati pot fi utilizati in cod apeland direct numele lor, fara operatorul punct `.`.
Folosind operatorul steluta `*`, se pot importa toti membrii unui modul si apoi utiliza apeland direct numele lor, fara a utiliza operatorul punct `.`. Aceasta tehnica nu se recomanda a fi folosita, deoarece poate determina conflicte de nume in codul apelant. De exemplu, daca se importa cu comanda `from` doua module si fiecare dintre acestea au definit cu acelasi nume un membru - o functie de exemplu, apelarea functiei respective in codul apelant, fara a se specifica prin operatorul punct `.` modulul care contine functia apelata, determina un conflict de nume, interpretorul nestiind care functie este apelata.

Sintaxa:

    from nume_modul import nume_membru_1, ...., nume_membru_n

sau

    from nume_modul import *

In [7]:

    # Exemplul 4 - importatea si modul de utilizare a unor membri specifici dintr-un modul

    from cats import cat_runs

    cat_runs()

Out[7]:

    "I'm running faster than wind!"

In [8]:

    # Exemplul 5 - importatea intregului modul cu comanda from si modul de utilizare a unor membri specifici dintr-un modul

    from cats import *
    print(ct.cat_eats())
    print(ct.cat_runs())

    Niam niam!
    I'm running faster than wind!