473,473 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

calling python functions using variables

Hi all!

this is a (relatively) newbie question
I am writing a shell in Python and I am facing a problem

The problem is, after taking the input from user, i have to execute the
command which is a python function

i invoke an 'ls' command like this
commands.ls()
where commands.py is a file in the same directory

what i want to do is
commands.VARIABLE()
where VARIABLE holds the name of the function which i want to execute
and depends on what the user has typed
what should i do to achieve that?

any help is appreciated

thank you

-creo
P.S. if you want me to clarify the question, please tell me so

May 19 '06 #1
12 1806
creo wrote:
i invoke an 'ls' command like this
commands.ls()
where commands.py is a file in the same directory

what i want to do is
commands.VARIABLE()
where VARIABLE holds the name of the function which i want to execute
and depends on what the user has typed


You want

getattr(commands, VARIABLE)()

Peter

May 19 '06 #2
Peter Otten <__*******@web.de> writes:
creo wrote:
what i want to do is
commands.VARIABLE()
where VARIABLE holds the name of the function which i want to execute
and depends on what the user has typed


You want

getattr(commands, VARIABLE)()


You'll also need to anticipate the situation where the value bound to
VARIABLE is not the name of an attribute in 'commands'.

Either deal with the resulting NameError exception (EAFP[0]) or test
first whether the attribute exists (LBYL[1]).

[0] Easier to Ask Forgiveness than Permission
[1] Look Before You Leap

--
\ "Our products just aren't engineered for security." -- Brian |
`\ Valentine, senior vice-president of Microsoft Windows |
_o__) development |
Ben Finney

May 19 '06 #3
Ben Finney wrote:
Peter Otten <__*******@web.de> writes: (snip)

You want
getattr(commands, VARIABLE)()


You'll also need to anticipate the situation where the value bound to
VARIABLE is not the name of an attribute in 'commands'.

Either deal with the resulting NameError exception (EAFP[0])


try:
getattr(commands, VARIABLE)()
except NameError:
print >> sys.stderr, "Unknown command", VARIABLE
or test
first whether the attribute exists (LBYL[1]).


command = getattr(commands, VARIABLE, None)
if command is None:
print >> sys.stderr, "Unknown command", VARIABLE
else:
command()

I'd go for the first solution.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 19 '06 #4
On 2006-05-19, bruno at modulix <on***@xiludom.gro> wrote:
Either deal with the resulting NameError exception (EAFP[0])


try:
getattr(commands, VARIABLE)()
except NameError:
print >> sys.stderr, "Unknown command", VARIABLE
or test
first whether the attribute exists (LBYL[1]).


command = getattr(commands, VARIABLE, None)
if command is None:
print >> sys.stderr, "Unknown command", VARIABLE
else:
command()

I'd go for the first solution.


Me too. Assuming the user isn't clueless, the normal case is
where the command exists. Write code for the normal case and
use the exception that occurs for exceptional cases.

--
Grant Edwards grante Yow! This PIZZA symbolizes
at my COMPLETE EMOTIONAL
visi.com RECOVERY!!
May 19 '06 #5
In article <12*************@corp.supernews.com>,
Grant Edwards <gr****@visi.com> wrote:
On 2006-05-19, bruno at modulix <on***@xiludom.gro> wrote:
Either deal with the resulting NameError exception (EAFP[0])


try:
getattr(commands, VARIABLE)()
except NameError:
print >> sys.stderr, "Unknown command", VARIABLE
or test
first whether the attribute exists (LBYL[1]).


command = getattr(commands, VARIABLE, None)
if command is None:
print >> sys.stderr, "Unknown command", VARIABLE
else:
command()

I'd go for the first solution.


Me too. Assuming the user isn't clueless, the normal case is
where the command exists. Write code for the normal case and
use the exception that occurs for exceptional cases.

May 19 '06 #6
Cameron Laird wrote:
Guys, I try--I try *hard*--to accept the BetterToAskForgiveness
gospel, but this situation illustrates the discomfort I consistently
feel: how do I know that the NameError means VARIABLE didn't resolve,
rather than that it did, but that evaluation of commands.VARIABLE()
itself didn't throw a NameError? My usual answer: umm, unless I go
to efforts to prevent it, I *don't* know that didn't happen.


two notes:

1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.

2) as you point out, doing too much inside a single try/except often results in hard-
to-find errors and confusing error messages. the try-except-else pattern comes in
handy in cases like this:

try:
f = getattr(commands, name)
except AttributeError:
print "command", name, "not known"
else:
f()

</F>

May 19 '06 #7

[Cameron]
try:
getattr(commands, VARIABLE)()
except NameError:
print >> sys.stderr, "Unknown command", VARIABLE

this situation illustrates the discomfort I consistently
feel: how do I know that the NameError means VARIABLE didn't resolve,
rather than that it did, but that evaluation of commands.VARIABLE()
itself didn't throw a NameError? My usual answer: umm, unless I go
to efforts to prevent it, I *don't* know that didn't happen.


The 'try' block should only include the code that you expect to fail with
the given exception. Try this instead:
try:
command = getattr(commands, VARIABLE)
except AttributeError:
print >> sys.stderr, "Unknown command", VARIABLE
else:
command()


(Aside: I think AttributeError is correct here, not NameError.)

--
Richie Hindle
ri****@entrian.com
May 19 '06 #8
Fredrik Lundh wrote:
Cameron Laird wrote:

Guys, I try--I try *hard*--to accept the BetterToAskForgiveness
gospel, but this situation illustrates the discomfort I consistently
feel: how do I know that the NameError means VARIABLE didn't resolve,
rather than that it did, but that evaluation of commands.VARIABLE()
itself didn't throw a NameError? My usual answer: umm, unless I go
to efforts to prevent it, I *don't* know that didn't happen.

two notes:

1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.


oops ! My bad :(
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
May 19 '06 #9
bruno at modulix <on***@xiludom.gro> writes:
Ben Finney wrote:
You'll also need to anticipate the situation where the value bound
to VARIABLE is not the name of an attribute in 'commands'.

Either deal with the resulting NameError exception (EAFP[0])


try:
getattr(commands, VARIABLE)()
except NameError:
print >> sys.stderr, "Unknown command", VARIABLE


No. As another poster points out, that will mistakenly catch NameError
exceptions raised *inside* the function.

When catching exceptions, be sure that your 'try' block is only doing
the minimum of stuff that you want exceptions from, so you know what
they mean when they occur.

try:
this_command = getattr(commands, VARIABLE)
except NameError:
print >> sys.stderr, "Unknown command '%s'" % VARIABLE
this_command()
or test first whether the attribute exists (LBYL[1]).


command = getattr(commands, VARIABLE, None)
if command is None:
print >> sys.stderr, "Unknown command", VARIABLE
else:
command()

I'd go for the first solution.


With the caveats mentioned above, yes, I agree.

--
\ "I was arrested today for scalping low numbers at the deli. |
`\ Sold a number 3 for 28 bucks." -- Steven Wright |
_o__) |
Ben Finney

May 20 '06 #10
"Fredrik Lundh" <fr*****@pythonware.com> writes:
Cameron Laird wrote:
how do I know that the NameError means VARIABLE didn't resolve,
rather than that it did, but that evaluation of
commands.VARIABLE() itself didn't throw a NameError? My usual
answer: umm, unless I go to efforts to prevent it, I *don't* know
that didn't happen.


two notes:

1) getattr() raises an AttributeError if the attribute doesn't
exist, not a NameError.

2) as you point out, doing too much inside a single try/except often
results in hard- to-find errors and confusing error messages. the
try-except-else pattern comes in handy in cases like this:

try:
f = getattr(commands, name)
except AttributeError:
print "command", name, "not known"
else:
f()


Gah. As is often the case, Frederick has avoided my mistakes and said
what I wanted to say, better.

--
\ "There are only two ways to live your life. One is as though |
`\ nothing is a miracle. The other is as if everything is." -- |
_o__) Albert Einstein |
Ben Finney

May 20 '06 #11
Fredrik Lundh wrote:
Cameron Laird wrote:
Guys, I try--I try *hard*--to accept the BetterToAskForgiveness
gospel, but this situation illustrates the discomfort I consistently
feel: how do I know that the NameError means VARIABLE didn't resolve,
rather than that it did, but that evaluation of commands.VARIABLE()
itself didn't throw a NameError? My usual answer: umm, unless I go
to efforts to prevent it, I *don't* know that didn't happen.


two notes:

1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError.

2) as you point out, doing too much inside a single try/except often results in hard-
to-find errors and confusing error messages. the try-except-else pattern comes in
handy in cases like this:

try:
f = getattr(commands, name)
except AttributeError:
print "command", name, "not known"
else:
f()


What if commands were an instance of this class:

class CommandClass:
....
def __getattr__(self,attr):
try:
return self.dircontenst[attr]
except KeyError:
raise AttributeError

The call to getattr manages to raise AttributeError even though the
command is known. Yes, self.dircontents[attr] does exist and is valid
in this example, but it still raises AttributeError because dircontents
is spelled wrong.

I make this silly example to point out that Python's dynamicism is a
possible pitfall with ETAFTP even if you're careful. It's something
worth keeping in mind.

Another example, much more realistic: GvR says don't use callable(),
just try calling it and catch CallableError (or whatever it is). Of
course, that error can be raised inside the function; and in this case,
there's no way to isolate only the part you you're checking for an
exception.
Carl Banks

May 20 '06 #12
Dennis Lee Bieber wrote:
On Fri, 19 May 2006 14:41:13 +0000, cl****@lairds.us (Cameron Laird)
declaimed the following in comp.lang.python: .
Guys, I try--I try *hard*--to accept the BetterToAskForgiveness
gospel, but this situation illustrates the discomfort I consistently
feel: how do I know that the NameError means VARIABLE didn't resolve,
rather than that it did, but that evaluation of commands.VARIABLE()


I'd suggest that each of your "valid" commands should contain
whatever error checking is appropriate to it -- and if needed, raise
some custom "command failure" exception after handling the real failure
internally.


That probably doesn't help when the exception is due to a bug and not
bad input. If you have an AttributeError due to a bug, it would be
wrong to raise a custom command failure exception.

Carl Banks

May 20 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

54
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO...
10
by: Kyler Laird | last post by:
I need to submit C/C++ code for a class. (It's not a programming class. The choice of language is inertial. I think that it mostly serves to distract students from the course subject.) I'm...
0
by: Natsu Mizutani | last post by:
Hello, I'm trying to wrap a c++ library using MPI inside with boost.python (or SWIG). I managed to find that calling `MPI::Init()` embeded in a c++ funtion would not work. So, I decided to use...
14
by: David MacQuigg | last post by:
I am starting a new thread so we can avoid some of the non-productive argument following my earlier post "What is good about Prothon". At Mr. Hahn's request, I will avoid using the name "Prothon"...
1
by: delrocco | last post by:
Hello, I really appreciate anyone who has time to read this and help, Thanks up front. I'm very new to python, having picked it up for the first time a week ago, but I feel I'm very close to...
6
by: Yevgeniy (Eugene) Medynskiy | last post by:
Hi all, This is probably a very newbie question, but after searching google and docs @ python.org I can't find an answer, so maybe someone would be able to help? I'd like to call command-line...
0
by: phoolimin | last post by:
Dear all, I am trying to embed python into another scripting language, to do this I need to solve a number of problems on importing or compiling python script. First let me state what exactly I...
3
by: Anthony Smith | last post by:
In my php page I am calling a Python cgi. The problem is that originally the Python script was being called directly and it could access the environment variables that were being set. Now since the...
0
marktang
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.