[Tutor] a quick Q: what does the "collapse" mean?
Steven D'Aprano
steve at pearwood.info
Thu Sep 8 16:56:54 CEST 2011
lina wrote:
> one example:
>
> def info(object, spacing=10, collapse=1):
> """Print methods and docs strings.
>
> Take modules, class, list, dictionary, or strong."""
> methodList = [e for e in dir(object) if callable(getattr(object, e))]
> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
> print "\n".join(["%s %s" %
> (method.ljust(spacing),
> processFunc(str(getattr(object, method).__doc__)))
> for method in methodList])
In this example, "collapse" is used as the name of an argument which
takes a true/false flag. If collapse is true, runs of whitespace is
collapsed into a single space:
"hello world" => "hello world"
The above function would be much easier to understand if it was written
like this:
def info(object, spacing=10, collapse=1):
"""Print methods and docs strings.
Take modules, class, list, dictionary, or string.
"""
method_names = []
doc_strings = []
for name in dir(object):
attribute = getattr(object, name)
if callable(attribute):
method_names.append(name.ljust(spacing))
doc_strings.append(str(attribute.__doc__))
if collapse:
doc_strings = [" ".join(doc.split()) for doc in doc_strings]
parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)]
print "\n".join(parts)
Much longer, but easier to follow for a beginner.
--
Steven
More information about the Tutor
mailing list