Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

class - python find the type of a function

I have a variable f. How can I determine its type? Here is my code, typed into a python interpreter, showing that I get an error using the successful pattern of the many examples I have found with Google. (Hint: I am very new to Python.)

>>> i=2; type(i) is int
True
>>> def f():
...     pass
... 
>>> type(f)
<class 'function'>
>>> type(i)
<class 'int'>
>>> type(f) is function
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> f=3
>>> type(f) is int
True

With f a function, I tried casting the return value of type(f) to a string, with u = str(type(f)). But when I tried u.print() I got an error message. This raises another question for me. Under Unix do error messages from Python come on stderr or stdout?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pythonic way to check the type of a function is using isinstance builtin.

i = 2
type(i) is int #not recommended
isinstance(i, int) #recommended

Python includes a types module for checking functions among other things.

It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.

So, to check if an object is a function, you can use the types module as follows

def f():
    print("test")    
import types
type(f) is types.FunctionType #Not recommended but it does work
isinstance(f, types.FunctionType) #recommended.

However, note that it will print false for builtin functions. If you wish to include those as well, then check as follows

isinstance(f, (types.FunctionType, types.BuiltinFunctionType))

However, use the above if you only want specifically functions. Lastly, if you only care about checking if it is one of function,callable or method, then just check if it behaves like a callable.

callable(f)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...