简体   繁体   中英

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 point_coords .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM