Yrogirg Yrogirg - 1 year ago 121
Python Question

How to determine function parameter type in python?

For example I have a poorly documented library. I have an object from it and I want to know what are the types of the arguments certain method accepts.

In IPython I can run

In [28]: tdb.getData?
Signature: tdb.getData(time, point_coords, sinterp=0, tinterp=0, data_set='isotropic1024coarse', getFunction='getVelocity', make_modulo=False)
Docstring: <no docstring>
File: ~/.local/lib/python3.5/site-packages/pyJHTDB/libJHTDB.py
Type: method

but it does not give me the types of the arguments. I don't know exactly what is the type of

Answer Source

Usually, functions in Python accept arguments of any type, so you cannot define what type it expects.

Still, the function probably does make some implicit assumptions about the received object.

Take this function for example:

def is_long(x):
    return len(x) > 1000

What type of argument x does this function accept? Any type, as long as it has length defined.

So, it can take a string, or a list, or a dict, or any custom object you create, as long as it implements __len__. But it won't take an integer.

is_long('abcd')  # ok
is_long([1, 2, 3, 4])  # ok
is_long(11)  # not ok

To answer the question: How can you tell what assumtions the function makes?

  • read the documentation
  • read the doc string (try help(funcname))
  • guess: Pass any argument to it and see how it fails. If it fails with AttributeError: X instance has no attribute 'get_value', it expects something with get_value.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download