473,804 Members | 2,127 Online
Bytes | Software Development & Data Engineering Community
+ 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 1113
On Apr 26, 6:17 pm, John Henry <john106he...@h otmail.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...@h otmail.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...@h otmail.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 __doubleundersc ore__ 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.loewi s.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...@h otmail.comwrote :
On Apr 26, 6:08*pm, "Martin v. Löwis" <mar...@v.loewi s.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...@h otmail.comwrote :
On Apr 26, 6:08 pm, "Martin v. Löwis" <mar...@v.loewi s.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
3865
by: Newgene | last post by:
Hi, group, I am trying to dynamically add a method to class by following this post: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ec2ad7a0a5d54a1/928e91be352c6bfc?q=%22new.code(%22+%22import+new&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3D%22new.code(%22+%22import+new%26qt_g%3D1%26&_doneTitle=Back+to+Search&&d#928e91be352c6bfc But I got the Error like the below: ...
1
311
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 still exist? Thanks for helping. Tobias
2
4705
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 whether its possible to display all of their names by iterating around something in the browser (suspect their not and you can't but its worth asking) Ta
0
1202
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 string argument of the function "DECIMAL"". That's clear. We are connecting to DB2 7.1 on MVS through DB2 Connect. Thanks for your help,
6
6727
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 : .... Var RecordNb : integer ; .... {Command : function of Access}
8
3393
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 actual program. To me "scope" of the name of a function or object are the general rules for the areas of a program that can through a declaration, have "visibility."
3
2123
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 "WaitSleepJoin" when it runs because the function it calls - "GenerateEvents()" has "Sleep()" function. Can I solve this problem with Thread? I don't want add nasty boll flags on it.
1
2925
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 compiler error C3385 "a function that has a DllImport Custom Attribute cannot return an instance of a class"
3
2697
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 - I tried using Handle but nothing happens Can anyone shed some light on how to use this function or give an example? Many Thanks TBS
13
7824
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 statement used in calling the function validateForm rather than being included inside the function? Thanks in advance,
0
9712
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10595
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7634
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6862
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5530
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4308
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.