4

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()
1
  • To answer the question in the title: Yes, classes are first-class value. You can bind them to variables, create new ones at run time, pass them around, etc. - type(f) == type(any_function_name_here) is nothing special, it just compares the two values resulting from some function call. Commented Jun 7, 2013 at 7:43

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

6

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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.