0

I have a function in my script that takes two arguments and save result to file:

def listing(val, ftype):

    with open(sys.argv[3], "a+") as myfile:
        myfile.write(val + ftype + '\n')
    return

but I want to use it when only one argument is provided. I can define argument as empty string '' like that:

listing('', '\n[*]Document files found:\n')

Is it the only way to deal with empty arguments?

2
  • If the argument is optional, the function declaration should say so: def listing(ftype, val=None). How the function then deals with the value internally is up to you. Commented Nov 8, 2017 at 15:05
  • using sys.argv[3] in your function sucks. Commented Nov 8, 2017 at 15:23

1 Answer 1

2

You could use default arguments for this purpose

Using Default Arguments

def listing(val, ftype=''):

    with open(sys.argv[3], "a+") as myfile:
       myfile.write(val + ftype + '\n')
    return

Calling : listing('\n[*]Document files found:\n') # need not give second argument

You could also make this a more generic function by taking variable number of arguments

def listing(*args):
     with open(sys.argv[3], "a+") as myfile:
          myfile.write("".join(args) + '\n')
     return

Calling: listing('String1','String2','String3')

Sign up to request clarification or add additional context in comments.

2 Comments

then myfile.write("".join(args) + '\n') will be better than the horrible loop
Thanks, generic vesion is the best for my needs, as I realized that I'm going to reuse this function even with more than 2 arguments, again thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.