Instantly share code, notes, and snippets.

Embed
What would you like to do?
Learning python parameters. Curious how to do a mix of arguments, with *args, keyword arguments with *kwargs
#!/usr/local/bin/python3
### Chris. Fauerbach.
### MIT License.
### Most flexible callback method signature if you have
### required and commonly expected keyword arguments
# fn
# callback is a required argument
# *args is everything optional
# counter is a named argument with a default value
# **kwargs is a way to get ANY other keyword arguments
def fn(callback, *args, counter=0, **kwargs):
print("-----------------")
print("fn: ", callback)
print(args)
print(kwargs)
print(kwargs['fake'])
if __name__ == "__main__":
fn("dog", fake="one")
"""
-----------------
fn: dog
()
{'fake': 'one'}
one
"""
fn("cat", "one", "two", fake='fake', counter=10, undefined=12)
"""
-----------------
fn: cat
('one', 'two')
{'fake': 'fake', 'undefined': 12}
fake
"""
fn("heather","another", fake="one")
"""
-----------------
fn: heather
('another',)
{'fake': 'one'}
one
"""
fn("frankenstein", fake="one")
"""
-----------------
fn: frankenstein
()
{'fake': 'one'}
one
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment