How do I say "Is this a function"?

Lie Lie.1296 at gmail.com
Sun Apr 27 13:49:19 EDT 2008


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.



More information about the Python-list mailing list