home ~ projects ~ socials

One Positional Argument With Optional Named Arguments In Python

This is the format for a python function with one required positional argument and multiple keyword arguments that can be made optional by passing a default value

NOTE: These functions are current disabled while messing with the indent setup for python

#+NAME: example_function #+begin_src python :post results_padder(data=*this*) :results output :wrap example :eval no

def example(main_input, *, key1, key2="default"): print(f"{main_input} - {key1} - {key2}")

#+end_src

#+NAME: example_output #+begin_src python :post results_padder(data=*this*) :results output :wrap example :noweb yes

<<example_function>>

example("asdf", key1="ting") example("asdf", key1="ting", key2="boop")

#+end_src

#+begin_example

asdf - ting - default asdf - ting - boop

#+end_example

If you run it without an argument, this happens:

<<example_function>>

  example()
Output:
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  TypeError: example() missing 1 required positional argument: 'main_input'

You can use the name of the positional argument as well (though, that seems weird to me) and then move the elements around

<<example_function>>

  example(key1="value1", main_input="value_main", key2="value2")
Output:
value_main - value1 - value2
-- end of line --