On 22 nov, 02:38, Chris <[EMAIL PROTECTED]> wrote:
> Hello everyone,
> I have a quick python question. Is they a better way of calling a
> method dynamically then what I have below? Is there a more elegant
> approach? Thanks in advance.

> try:
>     push = getattr(self, 'get_%s_content' % self.name)
> except AttributeError:
>     raise "Method does not exist"

<ot>
If that's how you handle the AttributeError, you'd be better doing
nothing - at least you'd get a meaningfull (at least for éa
developper) error message, and an helpful traceback.
</ot>


> if callable(push):
>     push(**argv)

There's no one-size-fits-all answer here. It depends on what you
consider to be 'normal' and 'exceptional' cases, on how you plan to
handle exceptional cases etc. But at least one thing is clear: your
solution is not consistant. Either
1/ you expect the attribute to exist *and* be callable - and then any
other case should raise the appropriate exception - or
2/ you consider that the attribute may exists *and* be callable if it
exists - in which case you should silently ignore a failure of getattr
() but raise if callable(obj) evals to False - or
3/ you just ignore both failure conditions.

Anyway, crashing on a gettattr() failure and ignoring a callable()
failure is really a WTF.

FWIW:

case 1/ is the simplest to code : just rely on Python's default error
handling:

push = getattr(obj, name) # will raise if no attribute 'name'
push(args) # will raise if 'push' is not callable


case 2/ is not that hard:

push = gettattr(obj, name, None)
if push and not callable(push):
    raise TypeError("%s.%s is not callable" % (obj, name))
push(args)

case 3/ is even simpler:

push = gettattr(obj, name, None)
if push and callable(push):
    push(args)


HTH


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to