[Tutor] How can I have type "function" in my script?

ALAN GAULD alan.gauld at btinternet.com
Wed May 9 00:06:44 CEST 2012

> > type(lambda : 0)
>> >
>> > is about as simple as you can do it with lambda...
>> ...I think there should be a type.function avaliable in python, like str, int, etc. exists. 
But there are many different function like objects just 
as there are many different types of number.  Python does 
not have a type.number either.

Instead of

> isinstance(2, function)you can do:


which will check if 2 is any kind of callable object 
- function, method, class etc.

That is usually much more useful that getting the type.

isinstance() does not of course return the type it tells 
you if the object is an instance of the class or any 
of its its subclasses:

>>> class C: pass
>>> class B(C):pass
>>> c = C()
>>> b = B()
>>> isinstance(c,C)
>>> isinstance(b,C)
>>> isinstance(b,B)
>>> isinstance(c,B)

callable works the same way in that it tests whether you 
can call the name. Which is usually all you care about.

> Yes, I know that the pythonic way is to not define types in variables. 
>> The variables are free while there is no assign to these. I need type because I want to implement 
>> Tag as triple of name, type and value. I want to differentiate between a tag with type str and 
>> value "today" and a tag with tag with type data and value "today".
But why? Doing so will greatly reduce the flexibility of your 
class. Far better to build Tag such that it works with any 
object type.

Why would you need to know the type?
There are a very few scenarios where the type is genuinely 
important (serialisation of data is one case) but in many 
cases you just don't need to know.

Alan G
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120508/657ea032/attachment.html>

More information about the Tutor mailing list