How do I say "Is this a function"?
John Henry
john106henry at hotmail.com
Sun Apr 27 19:11:28 EDT 2008
On Apr 27, 10:49 am, Lie <Lie.1... at gmail.com> wrote:
> On Apr 27, 11:01 am, John Henry <john106he... at hotmail.com> wrote:
>
>
>
> > On Apr 26, 6:08 pm, "Martin v. Löwis" <mar... at v.loewis.de> wrote:
>
> > > > 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.
More information about the Python-list
mailing list