473,471 Members | 1,964 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How do I say "Is this a function"?

How do I determine is something a function?

For instance, I don't want to relying on exceptions below:

def f1():
print "In f1"

def f3():
print "In f3"

def others():
print "In others"

for i in xrange(1,3):
fct = "f%d()"%(i+1)
try:
exec fct
except:
others()

I wish to say:

if value of fct is a funtion, invoke it, otherwise invoke others().

Thanks,
Jun 27 '08 #1
8 1089
On Apr 26, 6:17 pm, John Henry <john106he...@hotmail.comwrote:
How do I determine is something a function?

For instance, I don't want to relying on exceptions below:

def f1():
print "In f1"

def f3():
print "In f3"

def others():
print "In others"

for i in xrange(1,3):
fct = "f%d()"%(i+1)
try:
exec fct
except:
others()

I wish to say:

if value of fct is a funtion, invoke it, otherwise invoke others().

Thanks,
hasattr(fct, '__call__')

And be careful about using the exec statement.
Jun 27 '08 #2
callable(func) returns whether something is callable(will return true
for classes, functions, and objects with __call__ methods).

On Apr 26, 6:25*pm, Dan Bishop <danb...@yahoo.comwrote:
On Apr 26, 6:17 pm, John Henry <john106he...@hotmail.comwrote:
How do I determine is something a function?
For instance, I don't want to relying on exceptions below:
def f1():
* *print "In f1"
def f3():
* *print "In f3"
def others():
* *print "In others"
for i in xrange(1,3):
* *fct = "f%d()"%(i+1)
* *try:
* * * exec fct
* *except:
* * * others()
I wish to say:
* *if value of fct is a funtion, invoke it, otherwise invoke others().
Thanks,

hasattr(fct, '__call__')

And be careful about using the exec statement.
Jun 27 '08 #3
John Henry wrote:
How do I determine is something a function?

For instance, I don't want to relying on exceptions below:

def f1():
print "In f1"

def f3():
print "In f3"

def others():
print "In others"

for i in xrange(1,3):
fct = "f%d()"%(i+1)
try:
exec fct
except:
others()

I wish to say:

if value of fct is a funtion, invoke it, otherwise invoke others().

Thanks,
One way I would think of is:
str(type(fct)) == "<type 'function'>"

--
mph
Jun 27 '08 #4
Dan Bishop wrote:
On Apr 26, 6:17 pm, John Henry <john106he...@hotmail.comwrote:
>How do I determine is something a function?

For instance, I don't want to relying on exceptions below:
And why not?
>>
def f1():
print "In f1"

def f3():
print "In f3"

def others():
print "In others"

for i in xrange(1,3):
fct = "f%d()"%(i+1)
try:
exec fct
except:
others()

I wish to say:

if value of fct is a funtion, invoke it, otherwise invoke others().

Thanks,

hasattr(fct, '__call__')

And be careful about using the exec statement.
1. In the OP's code, fct is a string, e.g. "f2()", so hasattr(fct,
'__call__') will never return True.

2. Objects other than functions have a __call__ attribute. Some callable
objects don't have a __call__ attribute.

3. Use __doubleunderscore__ things only when you need them and only when
you know what you are doing. There are high-level built-in functions
such as callable and isinstance that can be used for such tests. The
literal answer to the OP's question is:

from types import FunctionType
if isinstance(fct, FunctionType):
do_something()

Something like the following will do the required trick (find callables
in the global namespace whose name matches a pattern) without using the
dreaded exec. Note I've left out the logic to call others; the OP's code
will call others once for each missing function ... let's leave him to
sort out whether that's a good idea or that should be changed to calling
it only once if all functions are missing.
>>def f1():
.... print "in f1"
....
>>def f3():
.... print "in f3"
....
>>globdict = globals()
globdict # output prettied manually
{'f1': <function f1 at 0x00BA0470>,
'f3': <function f3 at 0x00BA04F0>,
'__builtins__': <module '__builtin__' (built-in)>,
'__name__': '__main__',
'__doc__': None}
>>for i in xrange(1, 4): ### upper bound 3 probably a bug
.... fname = "f%d" % i
.... if fname in globdict:
.... func = globdict[fname]
.... if callable(func):
.... func()
....
in f1
in f3
>>>
Cheers,
John
Jun 27 '08 #5
def f1():
print "In f1"

def f3():
print "In f3"

def others():
print "In others"

for i in xrange(1,3):
fct = "f%d()"%(i+1)
try:
exec fct
except:
others()
I'd write that as

for i in xrange(1,3):
globals().get("f%d" % (i+1), others)()

Regards,
Martin
Jun 27 '08 #6
On Apr 26, 6:08*pm, "Martin v. Löwis" <mar...@v.loewis.dewrote:
def f1():
* *print "In f1"
def f3():
* *print "In f3"
def others():
* *print "In others"
for i in xrange(1,3):
* *fct = "f%d()"%(i+1)
* *try:
* * * exec fct
* *except:
* * * others()

I'd write that as

for i in xrange(1,3):
* * globals().get("f%d" % (i+1), others)()

Regards,
Martin
Perfect. Works great. No EXEC.

You guys are great.
Jun 27 '08 #7
Lie
On Apr 27, 11:01*am, John Henry <john106he...@hotmail.comwrote:
On Apr 26, 6:08*pm, "Martin v. Löwis" <mar...@v.loewis.dewrote:
def f1():
* *print "In f1"
def f3():
* *print "In f3"
def others():
* *print "In others"
for i in xrange(1,3):
* *fct = "f%d()"%(i+1)
* *try:
* * * exec fct
* *except:
* * * others()
I'd write that as
for i in xrange(1,3):
* * globals().get("f%d" % (i+1), others)()
Regards,
Martin

Perfect. *Works great. *No EXEC.

You guys are great.
If you just want to avoid exec, why not:

def f1:
print "In f1"
def f3:
print "In f3"

class f4(object):
def __init__(self):
print "In f4"

def others:
print "Since all else failed, I'm in others."

f2 = "NAF -Not a Function"

flist = [f1, f2, f3, f4]
for fct in flist:
try:
fct()
except TypeError:
others()

It's readable, and it's fast if there's just a few "hard fault" (try-
except works best when it usually succeed and just fails once or
twice), and it's Pythonic too (Easier to ask forgiveness than to ask
permission). The difference between this and the explicit type
checking is that this allows a class (like f4) to pass since a Class
Constructor & Initiator is a callable function too, depending on your
need, you might want to consider class constructor as a function too.
Jun 27 '08 #8
On Apr 27, 10:49 am, Lie <Lie.1...@gmail.comwrote:
On Apr 27, 11:01 am, John Henry <john106he...@hotmail.comwrote:
On Apr 26, 6:08 pm, "Martin v. Löwis" <mar...@v.loewis.dewrote:
def f1():
print "In f1"
def f3():
print "In f3"
def others():
print "In others"
for i in xrange(1,3):
fct = "f%d()"%(i+1)
try:
exec fct
except:
others()
I'd write that as
for i in xrange(1,3):
globals().get("f%d" % (i+1), others)()
Regards,
Martin
Perfect. Works great. No EXEC.
You guys are great.

If you just want to avoid exec, why not:

def f1:
print "In f1"
def f3:
print "In f3"

class f4(object):
def __init__(self):
print "In f4"

def others:
print "Since all else failed, I'm in others."

f2 = "NAF -Not a Function"

flist = [f1, f2, f3, f4]
for fct in flist:
try:
fct()
except TypeError:
others()

It's readable, and it's fast if there's just a few "hard fault" (try-
except works best when it usually succeed and just fails once or
twice), and it's Pythonic too (Easier to ask forgiveness than to ask
permission). The difference between this and the explicit type
checking is that this allows a class (like f4) to pass since a Class
Constructor & Initiator is a callable function too, depending on your
need, you might want to consider class constructor as a function too.
The reason I didn't want to do that is because when something goes
wrong inside the fcts, others gets executed. I wanted the program to
crash and burn rather than running others.
Jun 27 '08 #9

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

Similar topics

1
by: Newgene | last post by:
Hi, group, I am trying to dynamically add a method to class by following this post: ...
1
by: Tobias | last post by:
Need help: In Visual C++ 6 there was a feature "function called by" which could be reached by right-mouse-button-clicking on a function in the class view. I can't find the feature in .NET. Does it...
2
by: foldface | last post by:
Hi Subject says it all, how can I do this? Also, do things like string functions belong to any object? i.e. are they perhaps part of the window object but are a special case? I wondering...
0
by: Igor Orlanov | last post by:
I got the following error message: "Invalid character found in a character string argument of the function "1". What the function "1" could be? I've seen "Invalid character found in a character...
6
by: Clément Collin | last post by:
I working on a GIS project, with Access link which just need a little routine in VBA, but I haven't knowledges in VBA language. It's very simple, and it looks like that in a TPascal way : .......
8
by: TTroy | last post by:
I have a few questions about "scope" and "visibility," which seem like two different things. To me "visibility" of the name of a function or object is the actual code that can use it in an...
3
by: kiplring | last post by:
Suppose a function which has Sleep() method in it. And I want to recycle it. I made two buttons which call "Resume()" and "Suspend()". But It doesn't work. The state of thread "t" will be...
1
by: Sam | last post by:
I have a .dll with "C" functions that I need to call. One of the functions returns a simple struct(2 doubles) If I try to use DllImport like this: SomeStruct1 f1(SomeStruct1 *pS); I get...
3
by: Scott Gunn | last post by:
I have looked all over the net for an example on how to use this function but got no joy, lots of jargon explaining the function but no examples. In VB.Net the hwnd has gone there was one in vb6...
13
by: Steve | last post by:
On page 392 of "Javascript the definitive guide" a function is called like this:- <form action="processform.cgi" onsubmit="return validateForm();"> Why, in this instance, is the return...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.