Python – Introspection

Python – Introspection

In Python, as you will understand, everything in Python is an object , and the introspection technique is nothing more than code which examines other modules and functions in memory as objects, obtains information about them and those who handle them.

By the way, you will be able to define unnamed functions, call them to functions with unordered arguments, and you can refer to functions whose names we do not know.

Python through its interpreter

It is important to know Python through its interpreter due to several factors:

  • Know the classes, their own functions and attributes, through the introspection of the language.
  • Availability of consulting the language documentation from the interpreter, for a long time there was no Javadoc type documentation or class diagrams of the language itself, so many Python programmers got used to studying their code in this way, so I recommend that you use the interpret python for that.
  • Today there are tools that allow you to generate documentation from Python source codes such as Sphinx .

The easiest way is to start your relationship with Python by simply executing the command python in the following way:

python
Python 2.7.13 (default, Sep 26 2018, 18:42:22)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Must Read: Node.js – Features 

You can request the help of the Python interpreter by executing:

>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Welcome to Python 2.7!  This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

To run the available help on Python syntax, run the following command:

help> modules
Please wait a moment while I gather a list of all available modules... BaseHTTPServer asynchat imputil sha Bastion asyncore inspect shelve CDROM atexit io shlex CGIHTTPServer audiodev ipython_genutils shutil Canvas audioop itertools shutil_backports ConfigParser autoreload jinja2 signal Cookie babel json simplegeneric DLFCN backports keyword site Dialog base64 lib2to3 sitecustomize DocXMLRPCServer bdb linecache six FileDialog binascii linuxaudiodev smtpd FixTk binhex locale smtplib HTMLParser bisect logging sndhdr IN bsddb macpath snowballstemmer IPython bz2 macurl2path socket MimeWriter cPickle mailbox sphinx Queue cProfile mailcap sphinx_rtd_theme ScrolledText cStringIO markupbase spwd SimpleDialog calendar markupsafe sqlite3 SimpleHTTPServer cgi marshal sre SimpleXMLRPCServer cgitb math sre_compile SocketServer chunk md5 sre_constants StringIO cmath mhlib sre_parse TYPES cmd mimetools ssl Tix code mimetypes stat Tkconstants codecs mimify statvfs Tkdnd codeop mmap storemagic Tkinter collections modulefinder string UserDict colorsys multifile stringold UserList commands multiprocessing stringprep UserString compileall mutex strop _LWPCookieJar compiler NETRC struct _MozillaCookieJar contextlib new subprocess __builtin__ cookielib nis sūnau __future__ copy nntplib sunaudio _abcoll copy_reg ntpath symbol _ast crypt nturl2path sympyprinting _bisect csv numbers symtable _bsddb ctypes opcode sys _codecs curses operator sysconfig _codecs_cn cythonmagic optparse syslog _codecs_hk datetime os tabnanny _codecs_iso2022 dbhash os2emxpath tarfile _codecs_jp dbm ossaudiodev telnetlib _codecs_kr decimal parser tempfile _codecs_tw decorator pathlib2 termios _collections difflib pdb test _csv dircache pexpect tests _ctypes dis pickle textwrap _ctypes_test distutils pickleshare this _curses doctest pickletools thread _curses_panel docutils pip threading _elementtree dumbdbm pipes time _functools dummy_thread pkg_resources timeit _hashlib dummy_threading pkgutil tkColorChooser _heapq easy_install platform tkCommonDialog _hotshot email plistlib tkFileDialog _io encodings popen2 tkFont _json ensurepip poplib tkMessageBox _locale enum posix tkSimpleDialog _lsprof errno posixfile toaiff _md5 exceptions posixpath token _multibytecodec fcntl pprint tokenize _multiprocessing filecmp profile trace _osx_support fileinput prompt_toolkit traceback _pyio fnmatch pstats traitlets _random formatter pty ttk _scandir fpectl ptyprocess tty _sha fpformat pwd turtle _sha256 fractions py_compile types _sha512 ftplib pyclbr unicodedata _socket functools pydoc unittest _sqlite3 future_builtins pydoc_data urllib _sre gc pyexpat urllib2 _ssl gdbm pygments urlparse _strptime genericpath pytz user _struct getopt quopri uu _symtable getpass random uuid _sysconfigdata gettext re warnings _sysconfigdata_nd glob readline wave _testcapi grp repr wcwidth _threading_local gzip resource weakref _tkinter hashlib rexec webbrowser _warnings heapq rfc822 wheel _weakref hmac rlcompleter whichdb _weakrefset hotshot rmagic wsgiref abc htmlentitydefs robotparser xdrlib aifc htmllib runpy xml alabaster httplib scandir xmllib antigravity ihooks sched xmlrpclib anydbm imaplib select xxsubtype argparse imghdr sets zipfile array imp setuptools zipimport ast importlib sgmllib zlib Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam".

Then consult the module’s help os, running:

help> os
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

FILE
    /usr/lib/python2.7/os.py

MODULE DOCS
    https://docs.python.org/library/os

DESCRIPTION
    This exports:
      - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
      - os.path is one of the modules posixpath, or ntpath
      - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
      - os.curdir is a string representing the current directory ('.' or ':')
      - os.pardir is a string representing the parent directory ('..' or '::')
      - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
      - os.extsep is the extension separator ('.' or '/')
      - os.altsep is the alternate pathname separator (None or '/')
      - os.pathsep is the component separator used in $PATH etc
      - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
      - os.defpath is the default search path for executables
      - os.devnull is the file path of the null device ('/dev/null', etc.)

    Programs that import and use 'os' stand a better chance of being
    portable between different platforms.  Of course, they must then
    only use functions that are defined by all platforms (e.g., unlink
    and opendir), and leave all pathname manipulation to os.path
    (e.g., split and join).
 

Trick

Press the key qto exit the module help os.

Then press the Crtl + d key combination to exit help.

Then import the Python standard library called os, with the following command:

>>> import os
>>>
Previously imported the library you can use the function dir()to list or discover what attributes, methods of the class are available with the import
>>> dir(os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST',
'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE',
'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE',
'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_CREAT', 'O_DIRECT',
'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY',
'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC',
'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT',
'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict',
'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED',
'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG',
'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__',
'__doc__', '__file__', '__name__', '_copy_reg', '_execvpe', '_exists',
'_exit', '_get_exports_list', '_make_stat_result',
'_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result',
'_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown',
'chroot', 'close', 'confstr', 'confstr_names', 'ctermid', 'curdir',
'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error',
'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp',
'execvpe', 'extsep', 'fchdir', 'fdatasync', 'fdopen', 'fork', 'forkpty',
'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd',
'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups',
'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid',
'getsid', 'getuid', 'isatty', 'kill', 'killpg', 'lchown', 'linesep',
'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'makedirs',
'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty',
'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe',
'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink',
'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'setegid',
'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid',
'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp',
'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat',
'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result',
'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system',
'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam',
'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime',
'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']
>>>
Another example of use is to be able to use the method fileto determine the location of the imported library in the following way:

>>> os.__file__

‘/usr/lib/python2.7/os.pyc’ >>>

 

You can also consult the library documentation by osexecuting the following command:

>>> print os.__doc__
OS routines for NT or Posix depending on what system we're on.

This exports:
  - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
  - os.path is one of the modules posixpath, or ntpath
  - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
  - os.curdir is a string representing the current directory ('.' or ':')
  - os.pardir is a string representing the parent directory ('..' or '::')
  - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  - os.extsep is the extension separator ('.' or '/')
  - os.altsep is the alternate pathname separator (None or '/')
  - os.pathsep is the component separator used in $PATH etc
  - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
  - os.defpath is the default search path for executables
  - os.devnull is the file path of the null device ('/dev/null', etc.)

Programs that import and use 'os' stand a better chance of being
portable between different platforms.  Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
>>>

Execute the exit () command to exit the interpreter…

>>> exit()