[Tutor] Calling a function by string name
Smith, Jeff
jsmith at medplus.com
Fri Jul 21 21:32:08 CEST 2006
Fantastic...that really did the trick! I actually made one modification
since p4python allows you to run Perforce commands by calling them with
obj.run_COMMAND(args) so the final solution was:
def _p4run(self, method, *args):
'runs a Perforce command'
try:
if callable(method):
return method(*args)
elif hasattr(self._client, method) and
callable(getattr(self._client, method)):
return getattr(self._client, method)(*args)
elif hasattr(self._client, 'run_'+method) and
callable(getattr(self._client, 'run_'+method)):
return getattr(self._client, 'run_'+method)(*args)
elif hasattr(self._client, method):
raise TypeError(method) # not callable
else:
raise AttributeError(method) # no method/member with
that name
except p4.P4Client.error:
raise
except:
if self._client.errors:
raise p4.P4Client.error('\n'.join(self._client.errors))
else:
raise
Thanks,
Jeff
-----Original Message-----
From: Michael P. Reilly [mailto:arcege at gmail.com]
Sent: Friday, July 21, 2006 1:36 PM
To: Smith, Jeff
Cc: tutor at python.org
Subject: Re: [Tutor] Calling a function by string name
On 7/21/06, Smith, Jeff <jsmith at medplus.com> wrote:
I have an object and I want to call a method that I have constructed the
name for in a string.
For example:
str_method = 'myfun'
obj.str_method
Of course, this fails. I know I could probably do this with exec but is
there a better way?
For context, the specific application is a wrapper to calling p4python.
Note that the second return (under the else under the try) is where I
want to call 'method' which is the string name of a method valid for
self._client.
def _p4runner(self, method, *args):
'runs a Perforce command'
try:
if callable(method):
return method(*args)
elif hasattr(self._client, method) and callable(getattr(self._client,
method)):
return getattr(self._client, method)(*args)
elif hasattr(self._client, method):
raise TypeError(method) # not callable
else:
raise AttributeError(method) # no method/member with that name
else:
return self._client.method(*args)
except p4.P4Client.error:
raise
except:
if self._client.errors:
raise p4.P4Client.error('\n'.join(self._client.errors))
else:
raise
Clear as mud?
Crystally murky.
-Arcege
--
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060721/87f367b9/attachment.html
More information about the Tutor
mailing list