[Tutor] Getting import to use a variable name

Peter Otten __peter__ at web.de
Wed May 20 10:02:38 CEST 2015


Jim Mooney Py3.4.3winXP wrote:

> On 19 May 2015 at 17:25, Jim Mooney Py3.4.3winXP
> <cybervigilante at gmail.com> wrote:
> 
>>
>> If I can get dir to accept x I can parse the output to get rid of the
>> __xxx stuff and print it out.
>>
> 
> By that I mean dir will give me a list of strings I can then use __doc__
> on to get all useful help items.

If you start with an object dir() gives you a list of attribute names. To 
get the actual attributes use 

attribute = getattr(object, attribute_name)

Then print the attributes' docstring with

print(attribute_name, attribute.__doc__)

The complete example:

$ cat shorthelp.py
import importlib


def first_line(s):
    if s is None:
        return "(NO HELP AVAILABLE)"
    return s.splitlines()[0]


def shorthelp(obj):
    if isinstance(obj, str):
        # if obj is a string, assume it's a module name
        try:
            obj = importlib.import_module(obj)
        except BaseException as err:
            # we really don't want to exit on error
            print(err)
            return

    # documentation for obj
    objdoc = first_line(obj.__doc__)
    if objdoc:
        print(objdoc)
        print("-" * len(objdoc))

    # documentation for the attributes of obj
    names = [name for name in dir(obj) if not name.startswith("_")]
    width = max(len(name) for name in names)
    for name in names:
        print("{:{}}  {}".format(
            name, width,
            first_line(getattr(obj, name).__doc__)))

$ python3 -i shorthelp.py
>>> shorthelp("whatever")
No module named 'whatever'
>>> shorthelp(42)
int(x=0) -> integer
-------------------
bit_length   int.bit_length() -> int
conjugate    Returns self, the complex conjugate of any int.
denominator  int(x=0) -> integer
from_bytes   int.from_bytes(bytes, byteorder, *, signed=False) -> int
imag         int(x=0) -> integer
numerator    int(x=0) -> integer
real         int(x=0) -> integer
to_bytes     int.to_bytes(length, byteorder, *, signed=False) -> bytes
>>> shorthelp("pwd")
This module provides access to the Unix password database.
----------------------------------------------------------
getpwall       getpwall() -> list_of_entries
getpwnam       getpwnam(name) -> (pw_name,pw_passwd,pw_uid,
getpwuid       getpwuid(uid) -> (pw_name,pw_passwd,pw_uid,
struct_passwd  pwd.struct_passwd: Results from getpw*() routines.
>>> shorthelp(grp)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'grp' is not defined
>>> import grp
>>> shorthelp(grp)
Access to the Unix group database.
----------------------------------
getgrall      getgrall() -> list of tuples
getgrgid      getgrgid(id) -> tuple
getgrnam      getgrnam(name) -> tuple
struct_group  grp.struct_group: Results from getgr*() routines.




More information about the Tutor mailing list