Passing an optional argument in a function - python -


i create function can take either 1 or 2 arguments. currently, have function takes 2 arguments through cmd:

def test(self,countname,optionalarg):         if countname == "lowest":            #something         if optionalarg == "furthest:            #something         else:            #something else  if __name__ == '__main__':         countname = sys.argv[1]         optionalarg = sys.argv[2]          temp = len(sys.argv)         in xrange(1,temp):              sys.argv.pop() 

i run:

python filename.py lowest furthest

using means passing second arg must. if try run script passing 1 arg, encounters error (as expected). question is, how create optional argument, either passed or not, depending on situation?

for example:

python filename.py lowest

in situation, expect program perform "#something else" script, nothing passed , different "furthest".

please not write code me, here learn :)

this explained in finemanual(tm): https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions

note in python, expression defining default value optional argument eval'd ony once when def statement executed (which @ first import top-level function), can lead unexpected behaviours (cf "least astonishment" , mutable default argument).

also, "default value" has expression, not statement, cannot error handling here. wrt/ case trying use sys.argv[2] default value, it's wrong @ least 2 reasons:

  1. as noticed, breaks if len(sys.argv) < 3
  2. it makes function dependent on sys.argv, cannot reuse in different context

the right solution here handle user input (sys.argv or whatever) in "entry point" code (the __main__ section) - function should know nothing arguments values came (sys.argv, http request, text file or whatever).

so make long story short: use either hardcoded value (if makes sense) or "sentinel" value (none candidate) default value optional argument, , user inputs parsing in __main__ section (or better in main() function called __main__ section don't pollute module's namespace irrelevant variables):

def func(arg, optarg=none):     #code here   def main(*args):     #parse args     #call func right args  if __name__ == "__main__":     import sys      main(*sys.argv) 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -