Categories > Coding > Python >
Use of *args and **kwargs
Posted
As a result, I'm having trouble grasping the notion of *args and **kwargs.
So far, I have discovered:
*args = list of arguments - as positional arguments **kwargs = dictionary - whose keys become distinct keyword arguments and the values become values of these arguments
I'm not sure what programming task this would assist with.
Maybe:
Is it possible to pass lists and dictionaries as function parameters while also acting as a wildcard?
Is there a simple example of how *args and **kwargs are used?
In addition, the tutorial (source) I found just utilised the "*" and a variable name.
Are *args and **kwargs only placeholders, or do you actually utilise *args and **kwargs in the code?
Replied
I'll give you the answer you're looking for- *args and **kwargs are most commonly used to create optional arguments for, say, functions.
A required argument is created and used like this:
def MyFunc(argument):
return argument
# Usage
result = MyFunc(“Hello, World!â€)
print(MyFunc)
# Hello, World!
If the function is to be called without that argument provided, an error will occur as it is required.
*args and **kwargs are used to make optional arguments, like this: (using **kwargs)
def MyFunc(argument, **kwargs):
argument2 = kwargs.get(“argument2â€, “defaultvalueâ€)
return argument + argument2
# Usage
result = MyFunc(“Hello, “, argument2=“World!â€)
# Hello, World!
I don't know how to use *args but I do know how to use **kwargs, I hope this is somewhat helpful.
Cancel
Post
we are dead
Replied
@87922 pretty sure he uses javascript, plus i mean sometimes even pro's mess up and need a little help or some insight :D
Cancel
Post
Added
@87922 Sometimes it isn't that simple, some people have to take in information a certain way, maybe he couldn't find a good enough explanation for him online so he came to ask here :)
Cancel
Post
Ty for rep: Swiney, Byoke, Lion, Locust, Waves, Weeb, Nickk, darkn, Atari, CubeFaces, Lux14, Rice, Delta, Syraxes, Aeon, Jordan, Pluto, and Hiroku!
P.S, I like cats better too!
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Cancel
Post