Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call positional arguments explicitly from function call

I have a function with positional arguments. as the function is more complex (this is only to show you my purpose), i want to explicitly write in the function call the name of the arguments.

def my_function(a, b, *other):
    print(a)
    print(b)
    for item in other:
        print(item)

I want to avoid writing:

my_function(1, 2, 4,5,6)

and write it like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my_function(a=1, b=2, other=*[4,5,6])

python (3.x) does not allow writing things like my_function(a=1, b=2, 4,5,6) . we get this error because of the mapping SyntaxError: positional argument follows keyword argument

is there any way i could mention "other" in the signature ? it seems like all names of arguments must be named or nothing.

thanks if you have any tip.

>Solution :

No, once you use the first keyword argument when calling, all following arguments must be keyword arguments.

You cannot explicitly set the value to be assigned to the *args or **kwargs parameter, they will be collected according to the callers usage, E.g.,

def f(*args, **kwargs):
  print(f"{args=} {kwargs=}")
>>> f(args="a", kwargs="b")
args=() kwargs={'args': 'a', 'kwargs': 'b'}

An alternative may be to have other take a list of values, instead of using *args.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading