Advertisement
here2share

# func_args_and_kwargs.py

May 7th, 2015
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. # func_args_and_kwargs.py
  2.  
  3. def foo(a, b=3, *args, **kwargs):
  4.     print a, b, args, kwargs
  5. # Now, b will be explicitly set if you pass it as a keyword argument or the second positional argument
  6.  
  7. # Examples:
  8.  
  9. x,y,z,c,k = 1,2,3,4,5
  10.  
  11. foo(x) # a=x, b=3, args=(), kwargs={}
  12. foo(x, y) # a=x, b=y, args=(), kwargs={}
  13. foo(x, b=y) # a=x, b=y, args=(), kwargs={}
  14. foo(x, y, z, k) # a=x, b=y, args=(z, k), kwargs={}
  15. foo(x, c=y, d=k) # a=x, b=3, args=(), kwargs={'c': y, 'd': k}
  16. foo(x, c=y, b=z, d=k) # a=x, b=z, args=(), kwargs={'c': y, 'd': k}
  17. # foo(x, y, b=z) ### TypeError: foo() got multiple values for keyword argument 'b'
  18.  
  19. # Note: In particular, foo(x, y, b=z) doesn't work because b is assigned by position in that case
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement