Simulating "getopt" in functions (newbie)
Chris Liechti
cliechti at gmx.net
Sat Sep 7 16:31:25 EDT 2002
Thorsten Kampe <thorsten at thorstenkampe.de> wrote in
news:aldm7h$1orqou$1 at ID-77524.news.dfncis.de:
> Hi,
>
> I want to simulate a "getopt"-like behaviour within a _function_. This
> is to avoid having to define two functions: "function" and
> "slightly_different_function".
>
> If the function was a standalone program, it would work like this
> ("v" for "verbose"):
>
> $ function.py 5
> 1
>
> $ function.py -v 5
> The result is: 1
>
> I've thought of this to simulate it in a function:
> def function(a, b=None):
> if b == "v":
> print "The result is: 1"
> else:
> print "1"
>
>>>> function(5)
> 1
>
>>>> function(5, "v")
> The result is: 1
>
> So: what is the "pythonic", "natural" way to do this in Python?
your idea is right. i would however vary the details:
if you just want to swich something then somthing:
def function(a, verbose=0):
or you could use the presence of a file object in a param:
def function(a, output=None):
if output is not None:
output.write("The result is:)
print "1"
and i wouldn't use string parameters directly like you did. i someone makes
a typo within that string you wont get errors, but if you use a variable as
indirection you get a name error:
VEROSE="v"
function(23, VEROSE)
and using numbers instead of string would be more efficient.
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list