5.22. Getting help#
Two builtin functions that are incredibly useful for figuring out what attributes an object [1] has and what those attributes can do.
dir(some_variable)
lists the attributes ofsome_variable
, including methods.help(some_function)
displays helpful information about whatsome_function
does and how you use it
5.22.1. Examples of using dir()
and help()
#
Let’s create a list and see what it’s attributes are using dir()
.
data = []
dir(data)
['__add__',
'__class__',
'__class_getitem__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
Note
All attributes whose name begins with an underscore ("_"
) character are referred to as private attributes. At this point in your education you should ignore them.
So what are these things?
print(type(data.append))
<class 'builtin_function_or_method'>
Use help()
to figure out what can they do.
help(data.append)
Help on built-in function append:
append(object, /) method of builtins.list instance
Append object to the end of the list.
5.22.2. Type hints are useful!#
Python is known as a “duck-typing” language [2]. That said, many python functions and methods have definitions that are annotated with type hints. Think of these as the assumptions the function is making and an assumption that you can make regarding its output.
To illustrate this, I define a function below that has two arguments (a
, b
) that are both “expected” to be type int
. This is communicated by the : int
that follows the argument name. You can expect the function to return an int
, which is indicated by the -> int
following the closing parenthesis.
def add_ints(a: int, b: int) -> int:
return a + b
This phrase stems from the adage that “if it walks like a duck and talks like a duck, it is a duck.” In essence, Python programs work so long as the variable has the necessary attributes. This differs from typed languages, such as C
, where you must define in advance exactly what type every variable will be.
Those types are only considered hints because there is not actual type checking [3]! That function would work just fine if either of the input arguments was a float
too, so what good are type hints? Many modern programming editors also help guide your coding by alerting you when your program starts calling functions with types that don’t match function (or method) signatures. So, if you only call a function with the indicated types, your program is less likely to have bugs.
Tools such as mypy can do static type checking.