Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python have built in type values?

Tags:

python

types

Not a typo. I mean type values. Values who's type is 'type'.

I want to write a confition to ask:

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

Do I NEED to created a temporary function and do:

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

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

if type(f) == functionT : do_something()
like image 487
user48956 Avatar asked Dec 11 '22 14:12

user48956


2 Answers

For functions you would usually check

>>> callable(lambda: 0)
True

to respect duck typing. However there is the 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 shouldn't check type equality, instead use isinstance

>>> isinstance(lambda: 0, types.LambdaType)
True
like image 190
jamylak Avatar answered Dec 29 '22 00:12

jamylak


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

For example:

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__

The result:

IsFunction: True
h: helloworld
helloworld: helloworld

isfunction is preferred way to identify a function because a method from a 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)

The result:

IsFunction: False
Is callable: True
Type: <type 'instancemethod'>
like image 37
marcoseu Avatar answered Dec 28 '22 23:12

marcoseu