6 Replies - 507 Views - Last Post: 18 December 2012 - 07:46 AM Rate Topic: -----

#1 evthisal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 17-December 12

default argument and parameter values in python

Posted 17 December 2012 - 03:40 PM

Sorry, I already asked this a minute ago but I made a mistake and it wouldn't let me got back to edit and fix it so I'm reposting the question.

I have a python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the python file is run.
    ex:   
    myFile.py
    import sys
    def main(arg1....):
      ---code---

    --more functions--

    main()


When a person wants to run my file they'll type:
    python myFile.py arg1 arg2 ...


My question:
The main function is supposed to accept in x number of arguments, however, in case the user doesn't wish to pass in any arguments we're supposed to have default values.

my program looks something like this and I'm hoping there is actually a better way to do this than what I have:
    myFile.py
    import sys
    #Even though my function has default values, if the user doesn't wish
    #to input in any parameter values, they still must pass in the word False
    #otherwise, pls pass in parameter value
    def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"):
       if len(sys) > 1:
          i =0
          while i < len(sys):
             if i == 0:
                if sys.argv[i] == "False":
                   i += 1
                   continue
                else:
                    name = sys.argv[i]
                    i += 1
                    continue
             elif i == 1:
                if sys.argv[i] == "False":
         --------etc. etc.-----------


Is there a better way to do this?

Thank you in advance

Is This A Good Question/Topic? 0
  • +

Replies To: default argument and parameter values in python

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4325
  • View blog
  • Posts: 12,106
  • Joined: 18-April 07

Re: default argument and parameter values in python

Posted 17 December 2012 - 04:11 PM

Small tip just to help you out in the future. When you have an if statement like this...

if condition1:
   Do X
   Do Y
else:
   Do X
   Do Z



This is simply the same as...

Do X

if condition1:
   Do Y
else:
   Do Z



This is because no matter which statement you go into, you do X either way. This tells you that you should just do X and then do the if statement for the other statements.

But anyways... what is the purpose of checking for false again in your command line arguments? I have no idea what that is suppose to even be doing other than incrementing the counter "i". The idea behind default values is that if they don't supply a value, it gives it a value by default.

Are you trying to increment through the non-named arguments? :)
Was This Post Helpful? 1
  • +
  • -

#3 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3253
  • View blog
  • Posts: 10,908
  • Joined: 12-December 12

Re: default argument and parameter values in python

Posted 17 December 2012 - 04:24 PM

When your program is run it always calls main() straight-away with no arguments, only then does it begin to examine the command-line arguments (if any). So what you might be looking for is something like this:
import sys

def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"):
    pass # do something..

if len(sys) > 1:
    # assign values to arg1, arg2, etc.. some of which 
    # might be missing 
    # call main with these arguments:
    main(arg1, arg2, arg3, arg4)
else:
    main() # call it with no arguments, so defaults will be used


This is, however, a slightly unusual approach: there doesn't seem a need for the main() function unless it will be used again later on in your code.
Was This Post Helpful? 0
  • +
  • -

#4 Tayacan  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 275
  • Joined: 18-January 11

Re: default argument and parameter values in python

Posted 17 December 2012 - 05:03 PM

View Postevthisal, on 17 December 2012 - 10:40 PM, said:

while i < len(sys):
    if i == 0:
        if sys.argv[i] == "False":
            i += 1
            continue
        else:
            name = sys.argv[i]
            i += 1
            continue
    elif i == 1:
        if sys.argv[i] == "False":
    --------etc. etc.-----------



The quoted code can be vastly improved. Think about it. In your while loop, i first becomes 0, then 1, then 2, and so on up to some number. Inside the loop, you have a case for each of these numbers. That means that:

  • The first time the loop runs, the first case (i == 0) is run, and everything else is ignored.
  • The second time the loop runs, the second case (i == 1) is run, and everything else is ignored.
  • ...and so on.


The following pseudo code:
i = 0
while i < 3:
    if i == 0:
        doThing0()
    elif i == 1:
        doThing1()
    elif i == 2:
        doThing0()


is actually equivalent with this:
doThing0()
doThing1()
doThing2()


See the point? If nothing else is going on in your loop, you don't need it. Here's another tip that may or may not be of use to you:
l = [1,2,3]
a = l[0]
b = l[1]
c = l[2]

# Instead of writing that, we can simply do the following:
a,b,c = l


Was This Post Helpful? 1
  • +
  • -

#5 evthisal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 17-December 12

Re: default argument and parameter values in python

Posted 17 December 2012 - 05:41 PM

I tried to give an example instead of actually putting up my own code b/c I didn't want to violate any honor codes, but what my program basically does is take in x number of parameters. I know for sure that at the very least 2 parameters will be passed it and no more than 7 parameters can be passed in. However, the person running my program can pass in any number of parameters between 2 and 7. If he passed in 4 parameters, how would I know what variables they are associated with? My original plan was to have the user input in 7 parameters every time he runs my program and if he wanted to depend on my default values he will pass in the word "False" at the location I specified. For instance, in a README file I specified that if they want to only pass in 3 parameters, 2 file names and a score, they will have to run it like this
python myFile.py False False 56 False False file1.txt file2.txt. The two files are passed in at the end and the score is passed in at sys.argv[3]


Was This Post Helpful? 0
  • +
  • -

#6 Tayacan  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 145
  • View blog
  • Posts: 275
  • Joined: 18-January 11

Re: default argument and parameter values in python

Posted 18 December 2012 - 05:30 AM

Hmm. That, or you could have the user write something like this:
python myFile.py arg1=27 arg3=5 arg7=hey


That way, you can use string.split("=") to split each of them into a name and a value. If you want to make it even easier, you can use a dictionary instead of a bunch of variables, like this:
defaultArgs = {"arg1" : 34, "arg2" : 25, "arg3" : 0}
for arg in sys.argv:
    name,val = arg.split("=")
    defaultArgs[name] = val


Was This Post Helpful? 1
  • +
  • -

#7 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,596
  • Joined: 16-October 07

Re: default argument and parameter values in python

Posted 18 December 2012 - 07:46 AM

Not sure what we were going for here. My best guess:
import sys

def argDef(args, defArgs):
	def dArg(i):
		if len(args)<i or args[i]==None or args[i]=='False':
			return defArgs[i]
		return args[i]
	return [ dArg(i) for i in range(len(defArgs)) ]

def printListAndLables(labels, values):
	print(', '.join('{0}={1}'.format(k,v) for k,v in zip(labels, values) ) )

def test(name = None, age = None, num_pets = None, hobby = None):
	name, age, num_pets, hobby = argDef([name, age, num_pets, hobby], ["Bill", 22, 5, "soccer"])
	printListAndLables(('name', 'age', 'num_pets', 'hobby'),(name, age, num_pets, hobby))

def main():
	print(sys.argv)
	test(*sys.argv[1:])
	test(None, 'foo', 'False', 'Bar')
	test()

main()



Note, we make the test sig do the work for us. However, if we're looking for a command line option, then 'False' is less than intuitive.

Parsing command lines is nothing new and there are a number of ways to skin it. Here's one:
import sys
from optparse import OptionParser

def printListAndLables(labels, values):
	print(', '.join('{0}={1}'.format(k,v) for k,v in zip(labels, values) ) )

def process(cmdLine = None):
	parser = OptionParser("usage: %prog [options]")
	parser.add_option("-n", "--name", default='Bill')
	parser.add_option("-a", "--age", default=22)
	parser.add_option("-p", "--num-pets", default=5)
	parser.add_option("-b", "--hobby", default='soccer')
	
	if cmdLine: # nice for testing
		(opts, args) = parser.parse_args(cmdLine.split())
	else:
		(opts, args) = parser.parse_args()
	printListAndLables(('name', 'age', 'num_pets', 'hobby'),(opts.name, opts.age, opts.num_pets, opts.hobby))

def main():
	print(sys.argv)
	process()
	process("-n Alice -b hurley")
	process("-h")


main()



Note, the -h is implicit in the implementation. The OptionParser is a kitchen sink kind of tool. It can translate types, run programmatic actions, damn near everything you could think of for processing command line args.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1