Get argument types in python

I am learning python. I like to use help () or interinspect.getargspec to get information about functions in the shell. But still, I can get the argument / return type of the function.

+4
source share
4 answers

If you mean during a certain function call, the function itself can get the types of its arguments by calling type for each of them (and, of course, it will find out what type it will return).

If you mean from outside the function, no: the function can be called with arguments of any type - some of these calls will cause errors, but there is no way to know a priori which ones they will be.

Parameters can optionally be styled in Python 3, and one of the possible ways to use this styling is to express about the types of parameters (and / or other restrictions on them), but the language and the standard library do not give any indications of how such decoration can be used . You could also adopt the standard that such restrictions are expressed in a structured way in the docstring function, which has the advantage that it applies to any version of Python.

+4
source

The documentation 3.4.2 https://docs.python.org/3/library/inspect.html has a mention of what you need (namely, getting function argument types).

First you need to define your function as follows:

 def f(a: int, b: float, c: dict, d: list, <and so on depending on number of parameters and their types>): 

Then you can use formatargspec(*getfullargspec(f)) , which returns a good hash, for example:

 (a: int, b: float) 
+2
source

There is a function called type() .
Here are the docs

You cannot tell in advance what type the function returns

 >>> import random >>> def f(): ... c=random.choice("IFSN") ... if c=="I": ... return 1 ... elif c=="F": ... return 1.0 ... elif c=="S": ... return '1' ... return None ... >>> type(f()) <type 'float'> >>> type(f()) <type 'NoneType'> >>> type(f()) <type 'float'> >>> type(f()) <type 'int'> >>> type(f()) <type 'str'> >>> type(f()) <type 'float'> >>> type(f()) <type 'float'> >>> type(f()) <type 'NoneType'> >>> type(f()) <type 'str'> 

It is usually good practice to return only one type of object from a function, but Python does not force this on you

+1
source

An easy way is to use bpython

Learning Python is easy and fun again!

alt text http://www.noiseforfree.com/bpython/img/bpython01.png

0
source

Source: https://habr.com/ru/post/1300706/


All Articles