472,789 Members | 1,294 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,789 software developers and data experts.

other ways to check for <type 'function'>?

Hi there,

are there other ways than the ones below to check for <type 'function'>
in a python script?
(partly inspired by wrapping Tkinter :P)

def f():
print "This is f(). Godspeed!"

1.: --sort of clumsy and discouraged by the docs as far as I read
import types
type(f) is types.FunctionType

2.: --I don't like this one at all
def null(): pass
type(f) is type(null)

Basically I'm searching for something like:
"type(f) is func" like in: "type(x) is int"

Any ideas? =)

Nov 2 '06 #1
20 1988
elderic wrote:
are there other ways than the ones below to check for <type 'function'>
in a python script?
callable(f)

</F>

Nov 2 '06 #2
Thx =)

Fredrik Lundh schrieb:
elderic wrote:
are there other ways than the ones below to check for <type 'function'>
in a python script?

callable(f)

</F>
Nov 2 '06 #3
elderic enlightened us with:
are there other ways than the ones below to check for <type
'function'in a python script?
First of all, why would you want to? If you want to call the object
as a function, just do so. Handle the exception that is raised when
it's raised.

Sybren
--
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
Nov 2 '06 #4
Sybren Stuvel a écrit :
elderic enlightened us with:
>are there other ways than the ones below to check for <type
'function'in a python script?

First of all, why would you want to? If you want to call the object
as a function, just do so. Handle the exception that is raised when
it's raised.
I don't think it's a good idea because when you place a try catch block
around a function call, you'll catch any exception thrown by the
function itself and not only the "cannot be called" exception.
Nov 2 '06 #5
Sybren Stuvel schrieb:
elderic enlightened us with:
>are there other ways than the ones below to check for <type
'function'in a python script?

First of all, why would you want to? If you want to call the object
as a function, just do so. Handle the exception that is raised when
it's raised.
That's an advice I've heard a few times to often.

I'm totally buying duck-typing. Yet the advice of simply calling a
function to determine that it is one isn't sound in a lot of cases where
you want to use it as callback later on.

E.g. the turbogears DataGrid can get either a string or a callable
passed as column-data-provider. But which of these two options is used
must be known at construction time, not at later calling time.

Diez
Nov 2 '06 #6

Christophe wrote:
Sybren Stuvel a écrit :
elderic enlightened us with:
are there other ways than the ones below to check for <type
'function'in a python script?
First of all, why would you want to? If you want to call the object
as a function, just do so. Handle the exception that is raised when
it's raised.

I don't think it's a good idea because when you place a try catch block
around a function call, you'll catch any exception thrown by the
function itself and not only the "cannot be called" exception.
A little experimentation shows that when something is not callable
always a TypeError which evaluates to "'<type>' object is not
callable", so you can refine the try/catch with this information

pyx = 1
pyx()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
pyx = ''
pyx()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
pyclass x:
.... pass
....
pyx()
<__main__.x instance at 0x1002eef38>
pydef x():
py. pass
py.
pyx()

Nov 2 '06 #7
wi******@hotmail.com wrote:
A little experimentation shows that when something is not callable
always a TypeError which evaluates to "'<type>' object is not
callable"
that's not defined by the language specification, though, so your code
won't be portable, and may break in future releases.

and even if you can live with that, you still cannot distinguish between
non-callable objects and bugs *inside* the callables, unless you add
traceback analysis to the exception handler.

</F>

Nov 2 '06 #8
Christophe enlightened us with:
I don't think it's a good idea because when you place a try catch
block around a function call, you'll catch any exception thrown by
the function itself and not only the "cannot be called" exception.
That depends on the exception you're catching, doesn't it?

Sybren
--
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
Nov 2 '06 #9

elderic wrote:
Hi there,

are there other ways than the ones below to check for <type 'function'>
in a python script?
(partly inspired by wrapping Tkinter :P)

def f():
print "This is f(). Godspeed!"

1.: --sort of clumsy and discouraged by the docs as far as I read
import types
type(f) is types.FunctionType

2.: --I don't like this one at all
def null(): pass
type(f) is type(null)

Basically I'm searching for something like:
"type(f) is func" like in: "type(x) is int"

Any ideas? =)
you could use assert. Like the one below

assert inspect.isfunction(function_name)

Nov 2 '06 #10
Sybren Stuvel a écrit :
Christophe enlightened us with:
>I don't think it's a good idea because when you place a try catch
block around a function call, you'll catch any exception thrown by
the function itself and not only the "cannot be called" exception.

That depends on the exception you're catching, doesn't it?
And what if the function has an error and calls a non callable object ?
Nov 2 '06 #11

Fredrik Lundh wrote:
elderic wrote:
are there other ways than the ones below to check for <type 'function'>
in a python script?

callable(f)

</F>
PEP 3100 specifies that the callable builtin is
to be removed in Python 3.0, together with what
I presume is the underlying C support for the
function.

Unfortunately, there are cases where it's not
advisable to call something to verify that it's
callable - calling it will cause irreversable
changes to the program state, while a
verification function should make no changes
to state. The advice is fundamentally bad
design.

On the other claw, I can understand Guido's
point in wanting to get rid of it - it's got to be
an ugly piece of code with the Inappropriate
Intimacy code smell stinking up the place.

So what to do? Frankly, I'd back up a few
yards and consider the system design.
Where is the callable coming from? If it's
inside the team's scope of control, don't
bother checking it - the team should have
tests in place that verify that each site
passing a callable is passing the correct
object. If it's coming from outside, define
what's allowable and check that case by
case, preferably with consultation with
your code's clients.

John Roth

Nov 2 '06 #12
John Roth wrote:
PEP 3100 specifies that the callable builtin is
to be removed in Python 3.0, together with what
I presume is the underlying C support for the
function.
PEP 3100 is not even close to being finalized, and does not apply to
Python 2.X.

</F>

Nov 2 '06 #13
elderic:
1.: --sort of clumsy and discouraged by the docs as far as I read
import types
type(f) is types.FunctionType
What's the problem with this?

from types import FunctionType
if isinstance(f, FunctionType):
...

Bye,
bearophile

Nov 2 '06 #14
What's the problem with this?
>
from types import FunctionType
if isinstance(f, FunctionType):
...

Bye,
bearophile
Well... it's discouraged by the docs =)

At least the use of module types.
I was just wondering if there were some alternatives.
Never thought I would start off a thread this long =)

That was basically my reason for asking about something similar like
the functions list(), dict(), int(), etc... when called without (),
they return <type 'sometype'>.
I just wanted to know if there was a keyword for functions, too.

Then u could've done: type(f) is function
quite similar to: type(x) is int

Didn't intent to be a Documentation-Nazi *G*

-elderic

Excuse my large paste from the Python 2.5 Documentation:
---------------------------------------------------------------------------------------
5.15 types -- Names for built-in types

<snip!>

Typical use is for functions that do different things depending on
their argument types, like the following:

from types import *
def delete(mylist, item):
if type(item) is IntType:
del mylist[item]
else:
mylist.remove(item)

Starting in Python 2.2, built-in factory functions such as int() and
str() are also names for the corresponding types. This is now the
preferred way to access the type instead of using the types module.
Accordingly, the example above should be written as follows:

def delete(mylist, item):
if isinstance(item, int):
del mylist[item]
else:
mylist.remove(item)
---------------------------------------------------------------------------------------

Nov 2 '06 #15
Christophe a écrit :
Sybren Stuvel a écrit :
>Christophe enlightened us with:
>>I don't think it's a good idea because when you place a try catch
block around a function call, you'll catch any exception thrown by
the function itself and not only the "cannot be called" exception.

That depends on the exception you're catching, doesn't it?

And what if the function has an error and calls a non callable object ?
Or even worse. Since we have :
>>None()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'NoneType' object is not callable
>>1+""
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>""+1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

All of them are TypeError exceptions. It is extremly dangerous to put a
try except TypeError clause around a function call to catch the case
where the function object isn't a callable :/
Nov 2 '06 #16
elderic wrote:
I just wanted to know if there was a keyword for functions, too.

Then u could've done: type(f) is function
quite similar to: type(x) is int
but why do you think you need that, when you have callable() ? unless
you're doing specialized stuff, there's really no reason to distinguish
between function objects and other callables.

</F>

Nov 2 '06 #17
I just wanted to know if there was a keyword for functions, too.

Then u could've done: type(f) is function
quite similar to: type(x) is int

but why do you think you need that, when you have callable() ? unless
you're doing specialized stuff, there's really no reason to distinguish
between function objects and other callables.

</F>
I never said that I need anything - I merely asked for alternatives. =)
I'm pretty happy with the types-module or the callable() test.

Basically it's just for wrapping the creation of Tk-Buttons, etc.
They need a callback and in my process to learn I wanted to know about
the
possible options to test for that.

peace of mind. =)
elderic

Nov 2 '06 #18
elderic wrote:
I never said that I need anything - I merely asked for alternatives. =)
I'm pretty happy with the types-module or the callable() test.

Basically it's just for wrapping the creation of Tk-Buttons, etc.
They need a callback and in my process to learn I wanted to know about
the possible options to test for that.
the more reason not to even think about using anything but "callable".
many things in Python are callable; an explicit function test would
disallow several interesting alternatives:
>>def foo():
.... pass
....
>>class fum:
.... def bar(self):
.... pass
.... def __call__(self):
.... pass
....
>>type(foo) is type(fum)
False
>>f = fum()
type(foo) is type(f)
False
>>type(foo) is type(f.bar)
False

etc.

(and I really shouldn't ask why you cannot just use Tkinter, and spend
your time and energy on something more worthwhile ? if not else, there
are plenty of Tk extensions that could need nice wrappers...)

</F>

Nov 2 '06 #19
Python should have a TypeError subclass: "NotCallableError", to enforce
BAFP.

Nov 3 '06 #20
"ed************@gmail.com" <ed************@gmail.comwrites:
Python should have a TypeError subclass: "NotCallableError", to
enforce BAFP.
Bureau of Alcohol, Firearms, and Programmers?

(Perhaps you meant "EAFP")

--
\ "If you go flying back through time and you see somebody else |
`\ flying forward into the future, it's probably best to avoid eye |
_o__) contact." -- Jack Handey |
Ben Finney

Nov 3 '06 #21

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Steve Wilkinson | last post by:
I've just started using managed C++ with VS2005, so please forgive my ignorance. I'm investigating producing a managed wrapper for some functionality of the Windows Media Format SDK. I have the...
8
by: Rainer Queck | last post by:
Hi NG, I have a base class "Telegram". This class , as well as all descants have a static public field "public static int TelegramNo = <a tlg no>;" Now I added all descants of Telegram to a...
5
by: Luke | last post by:
Built-in functions don't bind to classes like regular functions. Is this intended? (I do notice that the Python Reference Manual sec 3.2 under "Class Instance" refers to a "user-defined...
1
by: =?Utf-8?B?RnJhbmNvaXNWaWxqb2Vu?= | last post by:
Hi there, Does anybody know how to return the results of an IEnumerable<typeas an array of the same type i.e type in a web service call without first having to collect all elements in the...
8
by: =?Utf-8?B?V2hpdG5leSBLZXc=?= | last post by:
Hi there, I'm having a bit of trouble using an HRASCONN object as a class member variable inside my managed C++ class. When I call RasDial() and pass in the address of my HRASCONN object, I get...
3
by: Dylan Nicholson | last post by:
Can someone confirm that a) is illegal, and b) the solution? a) namespace Test { struct MyStruct { int a; int b;
1
by: lovecreatesbea... | last post by:
In the following function `HardwareStatusDb()', If its arguments are declared as type of `string', I get: main.cpp:5: error: expected initializer before ‘int’. The error disappears when those...
5
by: Ronald S. Cook | last post by:
From my business tier (class) I get back an IQueryable<Penof data. Here is my client code that works fine: PenClass penClass = new PenClass(); IQueryable<Penpens = penClass.SelectPens(); ...
6
by: A.Rocha | last post by:
Hi, I need save to text file a List<type>, but i dont wont serialize. // List<mytypemyList = new List<mytype>(); anyone can help me? --
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.