Does python generate type values?

Not a typo. I mean type values. The values ​​that are printed are a "type".

I want to write an expression to ask:

if type(f) is a function : do_something() 

I need to create a temporary function and do:

 if type(f) == type(any_function_name_here) : do_something() 

or is it a built-in set of type types that i can use? Like this:

 if type(f) == functionT : do_something() 
+4
source share
2 answers

For functions you usually check

 >>> callable(lambda: 0) True 

respect duck typing. However, there is a types module:

 >>> import types >>> dir(types) ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__'] 

However, you should not check for type equality, use isinstance

 >>> isinstance(lambda: 0, types.LambdaType) True 
+7
source

The best way to determine if a variable is a function is inspect.isfunction . Once you have determined that a variable is a function, you can use the .__name__ attribute to determine the name of the function and perform the necessary verification.

For instance:

 import inspect def helloworld(): print "That famous phrase." h = helloworld print "IsFunction: %s" % inspect.isfunction(h) print "h: %s" % h.__name__ print "helloworld: %s" % helloworld.__name__ 

Result:

 IsFunction: True h: helloworld helloworld: helloworld 

isfunction is the preferred way to identify a function because the method from the class is also callable :

 import inspect class HelloWorld(object): def sayhello(self): print "Hello." x = HelloWorld() print "IsFunction: %s" % inspect.isfunction(x.sayhello) print "Is callable: %s" % callable(x.sayhello) print "Type: %s" % type(x.sayhello) 

Result:

 IsFunction: False Is callable: True Type: <type 'instancemethod'> 
+6
source

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


All Articles