Discussion:
[Tutor] Getting import to use a variable name
Jim Mooney Py3.4.3winXP
2015-05-19 23:45:07 UTC
Permalink
I use python help() a good deal but get tired of paging through the
__object__ stuff to get to what I use at my level, so I wrote the following
to omit it. The problem is, I want to import it then use it as shorthelp.py
for different modules so I could just type shorthelp(modulename). Only the
import mechanism won't let me rename. I can only use the hardcoded imported
module name, shutil in this case. If I try x = anothermodule, then import
x, it doesn't work. import sys.argv[1] also doesn't work. Is there any way
to get around this? I'm mostly interested in doing this from the repl
rather than running from the console.
Py3.4 win32

import shutil #this works to print non __xxx helpstrings for a module,
but I can't substitute it.
useful_helps = []
helps = dir(shutil)
for helper in helps:
if helper[0] == '_':
continue
useful_helps.append(helper)

for helper in useful_helps:
print(helper.upper() + ':', helper.__doc__, '\n')
--
Jim

After not doing dishes for a week and washing spoon after spoon, fork after
fork, knife after knife - I suddenly understand the mathematical concept of
infinity, which is just one more damn thing after another.
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Ben Finney
2015-05-20 00:18:11 UTC
Permalink
I can only use the hardcoded imported module name, shutil in this
case. If I try x = anothermodule, then import x, it doesn't work.
Can you show an example of Python code that you would like to work?
foo = 'barmodule'
import foo
That doesn't work because the ‘import’ statement requires the name
directly in the source, not as a string value.

You will be pleased to know of the standard library ‘importlib’
import importlib
foo = 'barmodule'
importlib.import_module(foo)
See the documentation for ‘importlib’ for more on this useful library
<URL:https://docs.python.org/3/library/importlib>.
--
\ “The restriction of knowledge to an elite group destroys the |
`\ spirit of society and leads to its intellectual |
_o__) impoverishment.” —Albert Einstein |
Ben Finney

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription
Jim Mooney Py3.4.3winXP
2015-05-20 00:25:30 UTC
Permalink
Post by Ben Finney
You will be pleased to know of the standard library ‘importlib’
import importlib
Yes, I already got importlib to accept a string. But I can't figure how to
Post by Ben Finney
x = 'shutil'
import importlib
importlib.__import__(x)
<module 'shutil' from 'C:\\Python34\\lib\\shutil.py'>
If I can get dir to accept x I can parse the output to get rid of the __xxx
stuff and print it out.
--
Jim

After not doing dishes for a week and washing spoon after spoon, fork after
fork, knife after knife - I suddenly understand the mathematical concept of
infinity, which is just one more damn thing after another.
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription o
Jim Mooney Py3.4.3winXP
2015-05-20 00:28:55 UTC
Permalink
Post by Jim Mooney Py3.4.3winXP
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.
--
Jim

After not doing dishes for a week and washing spoon after spoon, fork after
fork, knife after knife - I suddenly understand the mathematical concept of
infinity, which is just one more damn thing after another.
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Peter Otten
2015-05-20 08:02:38 UTC
Permalink
On 19 May 2015 at 17:25, Jim Mooney Py3.4.3winXP
Post by Jim Mooney Py3.4.3winXP
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
Post by Jim Mooney Py3.4.3winXP
shorthelp("whatever")
No module named 'whatever'
Post by Jim Mooney Py3.4.3winXP
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
Post by Jim Mooney Py3.4.3winXP
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.
Post by Jim Mooney Py3.4.3winXP
shorthelp(grp)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'grp' is not defined
Post by Jim Mooney Py3.4.3winXP
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.


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2015-05-20 09:15:58 UTC
Permalink
Post by Peter Otten
$ 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
...
Post by Peter Otten
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,
Thats pretty cool Peter. I can see me using that pretty often.
I think I'll be stealing that for my collection of useful tools. :-)

Kudos to Jim for the concept too.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Jim Mooney Py3.4.3winXP
2015-05-21 19:52:44 UTC
Permalink
Post by Peter Otten
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__)
Thanks. That will save a lot of scrolling - and saving scrolling and typing
is half the battle ;')
--
Jim
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...