Inspecting a function

We can use the type() function on any of these attributes to learn more about them. For instance, we can see that fetch_words is a function object:

>>> type(words.fetch_words)
<class 'function'>

We can in turn use dir() on the function to reveal its attributes:

>>> dir(words.fetch_words)
['__annotations__', '__call__', '__class__', '__closure__', '__code__',
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__get__', '__getattribute__', '__globals__',
'__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__',
'__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__']

We can see here that function objects have many special attributes to do with how Python functions are implemented behind the scenes. For now, we'll just look at a couple of simple attributes.

As you might expect, its __name__ attribute is the name of the function object as a string:

>>> words.fetch_words.__name__
'fetch_words'

Likewise, __doc__ is the docstring we provided, giving us some clues about how the built-in help() function might be implemented:

>>> words.fetch_words.__doc__
'Fetch a list of words from a URL. Args: url: The URL of a
UTF-8 text document. Returns: A list of strings containing
the words from the document. '

This is just a small example of how you can introspect Python objects at runtime, and there are many more powerful tools that you can use to learn more about the objects you're using. Perhaps the most instructive part of the example is that we were dealing with a function object, demonstrating that Python's pervasive object orientation includes elements of the language that may not be accessible at all in other languages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset