Tuesday, 17 January 2017

Python Interpreter: Help System

Last time, I talked about using the Python interpreter to calculate the cosine rule. Today, I intend to cover the interpreter in more detail.

One of the benefits of the interpreter is that it helps you to learn how to use an unfamiliar Python function. For instance, let's say I have forgotten whether the math.cos() function works in degrees or radians. What can I do?

Of course, one way is to look up the Python help documentation. But there is another convenient way, which is to type the following command in the interpreter:
>>> help(math.cos)
cos(x)

Return the cosine of x (measured in radians).

Straight away, I get the answer.

Note that you should import the math module for today's examples, as follows:
>>> import math 

Object Dir

Next, suppose I want to find out what is the function that computes the natural logarithm. I make a guess that the math module should have such a function. So, I can type the following command to check out what functions are inside the math module:
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__'
, 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh'
, 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc'
, 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum'
, 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan'
, 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi'
, 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']


The result shows 4 possible logarithm functions. So I try the first one as follows:
>>> help(math.log)
log(x[, base])

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.

Jackpot! It is easy, right?

Another way to do this is to get the help for the entire math module as follows:
>>> help(math)

This will get you the "docstrings" (explained below) of all the functions inside the math module.

Python Docstrings

The reason why the help() function works is because in Python, every module/function has a member called __doc__, which typically contains a brief description of the function.

This is also known as the "docstring", which what is printed out by the help() function.

I can also print out the "docstring" on my own with the following command:
>>> print(math.cos.__doc__)

Python __Dict__

Objects in Python have a special attribute named "__dict__". This stores the object's attributes. 
Since classes are also objects, therefore x.name is equivalent to trying the following in order: x.__dict__['name'], type(x).name.__get__(x, type(x)), type(x).name.

In a future post, I would like to discuss how to write functions using the interpreter.

No comments:

Post a Comment