DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Default Parameter in Python


The following codes demonstrates the default parameters usage in Python:

$ cat default_params.py
import sys
def myfunc(app_name, props='[]', master_name="yarn"):
    return "%s: method: %s; master_name: %s" % (app_name, props, master_name)
if __name__ == "__main__":
    if len(sys.argv) == 1:
        print(myfunc("default app", master_name='default master'))
    elif len(sys.argv) == 2:
        print(myfunc(sys.argv[1], master_name='local'))
    elif len(sys.argv) == 3:
        print(myfunc(sys.argv[1], sys.argv[2]))
    else:
        print(myfunc(sys.argv[1], sys.argv[2], sys.argv[3]))

$ python default_params.py
default app: method: []; master_name: default master

$ python default_params.py appname
appname: method: []; master_name: local

$ python default_params.py appname myprops
appname: method: myprops; master_name: yarn

$ python default_params.py appname proplist 'local[2]'
appname: method: proplist; master_name: local[2]

It's NOT recommended to use collection object (for example: list) as default parameters, see Default Parameter Values in Python for details.



Published

Feb 26, 2018

Last Updated

Feb 26, 2018

Category

Tech

Tags

  • function 4
  • parameter 1
  • python 136

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor