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, 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.
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.
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
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
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
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.
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.
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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:
...
|
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
|
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
|
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,
|
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}
| |
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."
|
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.
|
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"
|
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
|
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,
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |