pydoc

CLEPY - September Module of the month

Anurag Saxena

@_asaxena

  • pydoc is a builtin python module
  • nothing to install
  • automatically generates documentation from python modules

Example


In [9]:
! pydoc3 requests


Help on package requests:

NNAAMMEE
    requests

DDEESSCCRRIIPPTTIIOONN
    Requests HTTP Library
    ~~~~~~~~~~~~~~~~~~~~~
    
    Requests is an HTTP library, written in Python, for human beings. Basic GET
    usage:
    
       >>> import requests
       >>> r = requests.get('https://www.python.org')
       >>> r.status_code
       200
       >>> 'Python is a programming language' in r.content
       True
    
    ... or POST:
    
       >>> payload = dict(key1='value1', key2='value2')
       >>> r = requests.post('http://httpbin.org/post', data=payload)
       >>> print(r.text)
       {
         ...
         "form": {
           "key2": "value2",
           "key1": "value1"
         },
         ...
       }
    
    The other HTTP methods are supported - see `requests.api`. Full documentation
    is at <http://python-requests.org>.
    
    :copyright: (c) 2017 by Kenneth Reitz.
    :license: Apache 2.0, see LICENSE for more details.

PPAACCKKAAGGEE  CCOONNTTEENNTTSS
    __version__
    _internal_utils
    adapters
    api
    auth
    certs
    compat
    cookies
    exceptions
    help
    hooks
    models
    packages
    sessions
    status_codes
    structures
    utils

FFUUNNCCTTIIOONNSS
    cchheecckk__ccoommppaattiibbiilliittyy(urllib3_version, chardet_version)

DDAATTAA
    ____aauutthhoorr__eemmaaiill____ = 'me@kennethreitz.org'
    ____bbuuiilldd____ = 137473
    ____ccaakkee____ = '✨ 🍰 ✨'
    ____ccooppyyrriigghhtt____ = 'Copyright 2018 Kenneth Reitz'
    ____ddeessccrriippttiioonn____ = 'Python HTTP for Humans.'
    ____lliicceennssee____ = 'Apache 2.0'
    ____ttiittllee____ = 'requests'
    ____uurrll____ = 'http://python-requests.org'
    ccooddeess = <lookup 'status_codes'>

VVEERRSSIIOONN
    2.19.1

AAUUTTHHOORR
    Kenneth Reitz

FFIILLEE
    /usr/local/lib/python3.7/site-packages/requests/__init__.py


It essentially pulls out docstrings and presents them as documentation link

If there are no docstrings, pydoc will try an obtain the comment block that is right above the class, function, or method definition in the source file, or at the top of the module (__init__.py)

Back to requests

BTW I am using pydoc3 instead of pydoc because I have two version of python running (2.7 and 3.7)


In [10]:
! pydoc3 requests


Help on package requests:

NNAAMMEE
    requests

DDEESSCCRRIIPPTTIIOONN
    Requests HTTP Library
    ~~~~~~~~~~~~~~~~~~~~~
    
    Requests is an HTTP library, written in Python, for human beings. Basic GET
    usage:
    
       >>> import requests
       >>> r = requests.get('https://www.python.org')
       >>> r.status_code
       200
       >>> 'Python is a programming language' in r.content
       True
    
    ... or POST:
    
       >>> payload = dict(key1='value1', key2='value2')
       >>> r = requests.post('http://httpbin.org/post', data=payload)
       >>> print(r.text)
       {
         ...
         "form": {
           "key2": "value2",
           "key1": "value1"
         },
         ...
       }
    
    The other HTTP methods are supported - see `requests.api`. Full documentation
    is at <http://python-requests.org>.
    
    :copyright: (c) 2017 by Kenneth Reitz.
    :license: Apache 2.0, see LICENSE for more details.

PPAACCKKAAGGEE  CCOONNTTEENNTTSS
    __version__
    _internal_utils
    adapters
    api
    auth
    certs
    compat
    cookies
    exceptions
    help
    hooks
    models
    packages
    sessions
    status_codes
    structures
    utils

FFUUNNCCTTIIOONNSS
    cchheecckk__ccoommppaattiibbiilliittyy(urllib3_version, chardet_version)

DDAATTAA
    ____aauutthhoorr__eemmaaiill____ = 'me@kennethreitz.org'
    ____bbuuiilldd____ = 137473
    ____ccaakkee____ = '✨ 🍰 ✨'
    ____ccooppyyrriigghhtt____ = 'Copyright 2018 Kenneth Reitz'
    ____ddeessccrriippttiioonn____ = 'Python HTTP for Humans.'
    ____lliicceennssee____ = 'Apache 2.0'
    ____ttiittllee____ = 'requests'
    ____uurrll____ = 'http://python-requests.org'
    ccooddeess = <lookup 'status_codes'>

VVEERRSSIIOONN
    2.19.1

AAUUTTHHOORR
    Kenneth Reitz

FFIILLEE
    /usr/local/lib/python3.7/site-packages/requests/__init__.py


You can also look at classes of a package as just like you would call that class


In [11]:
! pydoc3 requests.get


Help on function get in requests:

rreeqquueessttss..ggeett = get(url, params=None, **kwargs)
    Sends a GET request.
    
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response


In [12]:
! pydoc3 requests.sessions


Help on module requests.sessions in requests:

NNAAMMEE
    requests.sessions

DDEESSCCRRIIPPTTIIOONN
    requests.session
    ~~~~~~~~~~~~~~~~
    
    This module provides a Session object to manage and persist settings across
    requests (cookies, auth, proxies).

CCLLAASSSSEESS
    builtins.object
        SessionRedirectMixin
            Session
    
    class SSeessssiioonn(SessionRedirectMixin)
     |  A Requests session.
     |  
     |  Provides cookie persistence, connection-pooling, and configuration.
     |  
     |  Basic Usage::
     |  
     |    >>> import requests
     |    >>> s = requests.Session()
     |    >>> s.get('http://httpbin.org/get')
     |    <Response [200]>
     |  
     |  Or as a context manager::
     |  
     |    >>> with requests.Session() as s:
     |    >>>     s.get('http://httpbin.org/get')
     |    <Response [200]>
     |  
     |  Method resolution order:
     |      Session
     |      SessionRedirectMixin
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  ____eenntteerr____(self)
     |  
     |  ____eexxiitt____(self, *args)
     |  
     |  ____ggeettssttaattee____(self)
     |  
     |  ____iinniitt____(self)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ____sseettssttaattee____(self, state)
     |  
     |  cclloossee(self)
     |      Closes all adapters and as such the session
     |  
     |  ddeelleettee(self, url, **kwargs)
     |      Sends a DELETE request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  ggeett(self, url, **kwargs)
     |      Sends a GET request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  ggeett__aaddaapptteerr(self, url)
     |      Returns the appropriate connection adapter for the given URL.
     |      
     |      :rtype: requests.adapters.BaseAdapter
     |  
     |  hheeaadd(self, url, **kwargs)
     |      Sends a HEAD request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  mmeerrggee__eennvviirroonnmmeenntt__sseettttiinnggss(self, url, proxies, stream, verify, cert)
     |      Check the environment and merge it with some settings.
     |      
     |      :rtype: dict
     |  
     |  mmoouunntt(self, prefix, adapter)
     |      Registers a connection adapter to a prefix.
     |      
     |      Adapters are sorted in descending order by prefix length.
     |  
     |  ooppttiioonnss(self, url, **kwargs)
     |      Sends a OPTIONS request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  ppaattcchh(self, url, data=None, **kwargs)
     |      Sends a PATCH request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  ppoosstt(self, url, data=None, json=None, **kwargs)
     |      Sends a POST request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
     |      :param json: (optional) json to send in the body of the :class:`Request`.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  pprreeppaarree__rreeqquueesstt(self, request)
     |      Constructs a :class:`PreparedRequest <PreparedRequest>` for
     |      transmission and returns it. The :class:`PreparedRequest` has settings
     |      merged from the :class:`Request <Request>` instance and those of the
     |      :class:`Session`.
     |      
     |      :param request: :class:`Request` instance to prepare with this
     |          session's settings.
     |      :rtype: requests.PreparedRequest
     |  
     |  ppuutt(self, url, data=None, **kwargs)
     |      Sends a PUT request. Returns :class:`Response` object.
     |      
     |      :param url: URL for the new :class:`Request` object.
     |      :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
     |      :param \*\*kwargs: Optional arguments that ``request`` takes.
     |      :rtype: requests.Response
     |  
     |  rreeqquueesstt(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)
     |      Constructs a :class:`Request <Request>`, prepares it and sends it.
     |      Returns :class:`Response <Response>` object.
     |      
     |      :param method: method for the new :class:`Request` object.
     |      :param url: URL for the new :class:`Request` object.
     |      :param params: (optional) Dictionary or bytes to be sent in the query
     |          string for the :class:`Request`.
     |      :param data: (optional) Dictionary, bytes, or file-like object to send
     |          in the body of the :class:`Request`.
     |      :param json: (optional) json to send in the body of the
     |          :class:`Request`.
     |      :param headers: (optional) Dictionary of HTTP Headers to send with the
     |          :class:`Request`.
     |      :param cookies: (optional) Dict or CookieJar object to send with the
     |          :class:`Request`.
     |      :param files: (optional) Dictionary of ``'filename': file-like-objects``
     |          for multipart encoding upload.
     |      :param auth: (optional) Auth tuple or callable to enable
     |          Basic/Digest/Custom HTTP Auth.
     |      :param timeout: (optional) How long to wait for the server to send
     |          data before giving up, as a float, or a :ref:`(connect timeout,
     |          read timeout) <timeouts>` tuple.
     |      :type timeout: float or tuple
     |      :param allow_redirects: (optional) Set to True by default.
     |      :type allow_redirects: bool
     |      :param proxies: (optional) Dictionary mapping protocol or protocol and
     |          hostname to the URL of the proxy.
     |      :param stream: (optional) whether to immediately download the response
     |          content. Defaults to ``False``.
     |      :param verify: (optional) Either a boolean, in which case it controls whether we verify
     |          the server's TLS certificate, or a string, in which case it must be a path
     |          to a CA bundle to use. Defaults to ``True``.
     |      :param cert: (optional) if String, path to ssl client cert file (.pem).
     |          If Tuple, ('cert', 'key') pair.
     |      :rtype: requests.Response
     |  
     |  sseenndd(self, request, **kwargs)
     |      Send a given PreparedRequest.
     |      
     |      :rtype: requests.Response
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  ____aattttrrss____ = ['headers', 'cookies', 'auth', 'proxies', 'hooks', 'params...
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from SessionRedirectMixin:
     |  
     |  ggeett__rreeddiirreecctt__ttaarrggeett(self, resp)
     |      Receives a Response. Returns a redirect URI or ``None``
     |  
     |  rreebbuuiilldd__aauutthh(self, prepared_request, response)
     |      When being redirected we may want to strip authentication from the
     |      request to avoid leaking credentials. This method intelligently removes
     |      and reapplies authentication where possible to avoid credential loss.
     |  
     |  rreebbuuiilldd__mmeetthhoodd(self, prepared_request, response)
     |      When being redirected we may want to change the method of the request
     |      based on certain specs or browser behavior.
     |  
     |  rreebbuuiilldd__pprrooxxiieess(self, prepared_request, proxies)
     |      This method re-evaluates the proxy configuration by considering the
     |      environment variables. If we are redirected to a URL covered by
     |      NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
     |      proxy keys for this URL (in case they were stripped by a previous
     |      redirect).
     |      
     |      This method also replaces the Proxy-Authorization header where
     |      necessary.
     |      
     |      :rtype: dict
     |  
     |  rreessoollvvee__rreeddiirreeccttss(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
     |      Receives a Response. Returns a generator of Responses or Requests.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from SessionRedirectMixin:
     |  
     |  ____ddiicctt____
     |      dictionary for instance variables (if defined)
     |  
     |  ____wweeaakkrreeff____
     |      list of weak references to the object (if defined)
    
    class SSeessssiioonnRReeddiirreeccttMMiixxiinn(builtins.object)
     |  Methods defined here:
     |  
     |  ggeett__rreeddiirreecctt__ttaarrggeett(self, resp)
     |      Receives a Response. Returns a redirect URI or ``None``
     |  
     |  rreebbuuiilldd__aauutthh(self, prepared_request, response)
     |      When being redirected we may want to strip authentication from the
     |      request to avoid leaking credentials. This method intelligently removes
     |      and reapplies authentication where possible to avoid credential loss.
     |  
     |  rreebbuuiilldd__mmeetthhoodd(self, prepared_request, response)
     |      When being redirected we may want to change the method of the request
     |      based on certain specs or browser behavior.
     |  
     |  rreebbuuiilldd__pprrooxxiieess(self, prepared_request, proxies)
     |      This method re-evaluates the proxy configuration by considering the
     |      environment variables. If we are redirected to a URL covered by
     |      NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
     |      proxy keys for this URL (in case they were stripped by a previous
     |      redirect).
     |      
     |      This method also replaces the Proxy-Authorization header where
     |      necessary.
     |      
     |      :rtype: dict
     |  
     |  rreessoollvvee__rreeddiirreeccttss(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
     |      Receives a Response. Returns a generator of Responses or Requests.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  ____ddiicctt____
     |      dictionary for instance variables (if defined)
     |  
     |  ____wweeaakkrreeff____
     |      list of weak references to the object (if defined)

FFUUNNCCTTIIOONNSS
    mmeerrggee__hhooookkss(request_hooks, session_hooks, dict_class=<class 'collections.OrderedDict'>)
        Properly merges both requests and session hooks.
        
        This is necessary because when request_hooks == {'response': []}, the
        merge breaks Session hooks entirely.
    
    mmeerrggee__sseettttiinngg(request_setting, session_setting, dict_class=<class 'collections.OrderedDict'>)
        Determines appropriate setting for a given request, taking into account
        the explicit setting on that request, and the setting in the session. If a
        setting is a dictionary, they will be merged together using `dict_class`
    
    pprreeffeerrrreedd__cclloocckk = time(...)
        time() -> floating point number
        
        Return the current time in seconds since the Epoch.
        Fractions of a second may be present if the system clock provides them.
    
    sseessssiioonn()
        Returns a :class:`Session` for context-management.
        
        :rtype: Session

DDAATTAA
    DDEEFFAAUULLTT__RREEDDIIRREECCTT__LLIIMMIITT = 30
    RREEDDIIRREECCTT__SSTTAATTII = (301, 302, 303, 307, 308)
    ccooddeess = <lookup 'status_codes'>
    iiss__ppyy33 = True

FFIILLEE
    /usr/local/lib/python3.7/site-packages/requests/sessions.py


You can also run a pydoc server with the command pydoc -b. This is more user friendly as it opens in a browser and you can point and click or just have it open when you are coding.

That is all folks!