Positional-only and keyword-only arguments in Python
Skills:
RAG Basics80%
Key Takeaways
This video demonstrates how to define positional-only and keyword-only arguments in Python using the star (*) operator and slash (/) in the argument list, with examples and use cases for each.
Full Transcript
hey james murphy here with m coding in this episode we're talking about positional only and keyword only arguments in python this is a normal function definition with three arguments a b and c as is we can pass any of the arguments as either positional or keyword arguments here we pass them all as positional arguments and here we give all keyword arguments the order of the arguments doesn't matter when we use keyword arguments and we can mix and match passing some parameters as positional and some as keyword arguments you do have to pass all of your positional arguments first though so this is an error this gives callers of the function f a lot of flexibility in how they want to call it but sometimes we don't want to give them all that flexibility and for those cases we can actually require that certain arguments are passed as positional arguments or require that they're passed as keyword arguments let's see how syntactically you would make an argument either positional or keyword only and then more importantly let's see why you would ever want to do this let's start with keyword only arguments inside your parameters put a star the arguments before the star can still be passed either as positional or keyword arguments things after the star now have to be passed as keyword arguments or they could be omitted if they have a default value i guess obviously if you try to pass a keyword argument as a positional argument you get a syntax error we're going to have stars and slashes and star stars and it might be a bit tricky to remember here's the way that you should remember that everything after the star is a keyword argument recall what star args does star args eats all remaining positional arguments in this case our positional arguments are 1 and 2 which line up with a and b there aren't any more positional arguments so args just becomes the empty tuple if we pass additional positional arguments that's where they show up okay great args swallows up anything that's positional so logically anything that comes after star args can't be positional otherwise it would have just been part of args so this is actually another way to force an argument to be a keyword only argument anything that comes after star args or star whatever variable name must be a keyword only argument that's how i remember that everything after a star is keyword only i'm just imagining it's short for star args but i don't care about the args variable but the plain star actually has a benefit over using star args unlike star args the plane star does not swallow up all the rest of the positional arguments so this call where i have four positional arguments is an error whereas if i used star args that 3 and 4 would just get swallowed up this can be a problem because it gives the accidental opportunity to pass in something that you didn't mean to you could check to see if there were any extraneous positional arguments that were passed in and then raise an error if there are but that's just a lot of extra unnecessary work instead just use a star and don't give it a name okay but why would you want a keyword only argument keyword-only arguments are most often used as options or settings that slightly vary or modify the behavior of some code this combined function just takes two iterables and then puts them one after another into a big list maybe we want to add some kind of validation to this function if you passed in a callable validator then we check that all the elements are valid we could just leave validator as a normal argument but then it's possible someone sees a correct usage of this combine sub and scribe and maybe they don't quite look at the documentation and they think that they can just combine any number of things in this case we will get an error but it's not the one that i would hope we get the string is taken as the validator then we'll get a crash when we try to use the string as a callable object which it's not if the thing that i tried to pass here happened to have a similar enough interface to a validator we might have gotten the worst case no errors at all a silent wrong answer instead we use a star and make validator a keyword only argument now this caller will get the correct error that they passed too many positional arguments you can also use this to force your caller to spell out exactly what argument they're passing in this can be useful if you really really want to make sure that two arguments aren't mixed up you wouldn't want to mix up buying 10 000 of something at a price of 4 500 and buying 4 500 of something at a price of 10 000. using keyword arguments can minimize the risk of this very plausible human error what about positional only arguments here's the syntax in your argument list put a slash there's no equivalent of starags for slash this is the only way you use it any parameters before the slash must be passed as positional so it ends up looking like this positional arguments first then the slash then normal arguments they can be passed either as positional or keyword arguments then a star then keyword-only arguments you can even throw in star star quarks to catch all remaining keyword arguments i know this notation is kind of annoying to remember i always start with the star star is like star args that eats all positional arguments anything to the right is keyword arguments and the things to the very left must be positional of course you can mix and match all of these a slash directly followed by a star is a common pattern to force all of the arguments to either be positional only or keyword only a slash at the end means everything is positional a star at the beginning means everything is keyword only but the only way to really get the hang of it is to just try a few okay now what are the actual use cases for positional only arguments consider this function check truthy it checks that the argument x is truthy and otherwise raises an error the context of this function is incredibly general it wouldn't be specific to any particular domain or part of a program so why is its argument name x well it's named x because variables need names and i just picked x but x is not a meaningful name for this argument and i claim that there really is no meaningful name i mean you could call it object or something like that but is that really that meaningful when you use this function just pass in whatever you want to check as truthy this argument is best portrayed just as the argument to the function it doesn't need and it shouldn't have a name like x so in this case we use the slash at the end of the argument list to force it to be a positional only argument if i do this then at some later time i'd be free to change the name x to something else for instance later i might want to decide that i want to check any number of arguments for truthiness i can change x into star valves and then loop over the x's because none of the people calling this function referred to the variable x this is now a completely backwards compatible change another use case that i find often comes up with positional arguments is when the placement of the variables mimics some kind of mathematical expression in this case i'm looking at raising x to the y power and taking it mod some number in this case the names x and y don't really convey which one is being raised to the other power it's more the fact that x comes first and y comes second that x is being raised to the y and in this case i think actually specifying the modulus this way makes it even more clear so to me it makes sense to additionally make mod a keyword only argument what about all three is there any case where you really want positional only positional or keyword and keyword only in fact there are zero examples of this in the entire python standard library with the exception of the tests that this feature works there are a few cases though where you do this where all of the arguments are positional only or keyword only the best example i could find of this is actually the data class decorator data classes have tons of different features that you can turn on and off so those make sense as keyword only arguments but dataclass is a decorator so by definition it takes a single callable as an argument so i guess yeah that makes sense whatever it applies to is the unique positional argument and finally let's do a speed test are positional arguments faster than keyword arguments and what if they're positional only or keyword only arguments how do the timings of all of those compare don't bother reading all the code exactly here's the setup i have a normal function with three regular parameters and i call it with positional keyword arguments out of order keyword arguments and a mixture then i redefine the function making everything positional only again time that then redefine again and make everything keyword only and then time that in order and out of order then i just print out all the times and here the timing results all the numbers are in nanoseconds so these are all really fast it's pretty clear there's a slight but statistically significant difference we have 77 and 78 and any of the variations that used any keyword arguments used at least 95 nanoseconds so yes positional arguments are faster than keyword arguments it didn't seem to make any difference if they were positional only versus if you just happened to pass them as positional thank you all for listening that's all i've got thank you to my patrons and donors for supporting me if you enjoy my content please consider becoming a patron on patreon as always don't forget to subscribe and slap that like button an odd number of times see you next time
Original Description
Make function args positional or keyword-only.
In Python, it's possible to force a function argument to be positional-only or keyword-only. In this video, we see the syntax for doing this, as well as see some examples and reasons for why you might want to actually make a parameter positional-only or keyword-only.
Note: positional-only arguments are a Python 3.8+ feature. Keyword-only are Python 3.0+.
Errata:
1. At 1:22 you'll get a TypeError, not a SyntaxError.
― mCoding with James Murphy (https://mcoding.io)
Source code: https://github.com/mCodingLLC/VideosSampleCode
Positional-only PEP: https://peps.python.org/pep-0570/
Keyword-only PEP: https://peps.python.org/pep-3102/
SUPPORT ME ⭐
---------------------------------------------------
Patreon: https://patreon.com/mCoding
Paypal: https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE
Other donations: https://mcoding.io/donate
Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, John Martin, Casey G
BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord: https://discord.gg/Ye9yJtZQuN
Github: https://github.com/mCodingLLC/
Reddit: https://www.reddit.com/r/mCoding/
Facebook: https://www.facebook.com/james.mcoding
CHAPTERS
---------------------------------------------------
0:00 Intro
1:08 Keyword-only arguments
4:50 Positional-only arguments
7:45 Uncommon to use both
8:29 Speed test, position args are faster
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from mCoding · mCoding · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
Python's comma equals ,= operator?
mCoding
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
JSON Tutorial Python | Basic Python Recipes
mCoding
Simulating Brownian Motion in Python
mCoding
The Single Most Useful Decorator in Python
mCoding
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
Numpy Array Broadcasting In Python Explained
mCoding
Brownian Motion Single Path Zoom
mCoding
Brownian Motion Fractal Zoom
mCoding
Magic Methods - Making Python builtins work with your classes
mCoding
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
How Fast is Python's Sort? Performance Testing
mCoding
C++ First Missing Int, faster than 100%!
mCoding
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
Python dataclasses will save you HOURS, also featuring attrs
mCoding
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
Python's sharpest corner is ... plus equals? (+=)
mCoding
Binary Search - A Different Perspective | Python Algorithms
mCoding
The Best Way to Check for Optional Arguments in Python
mCoding
Local and Global Variable Lookup Weirdness in Python
mCoding
Efficient Exponentiation
mCoding
How To Install Python for Data Science
mCoding
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
Python 3.10's new type hinting features
mCoding
Python 3.10's Quality of Life improvements
mCoding
Introducing mZips! Python Zip and Zip Longest
mCoding
Match statement tips
mCoding
Using except: is a HUGE mistake
mCoding
Python + YouTube API | Automating descriptions
mCoding
Anaphones, phonetic anagrams
mCoding
Cracking passwords using ONLY response times | Secure Python
mCoding
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
Diagnose slow Python code. (Feat. async/await)
mCoding
Python MD5 implementation
mCoding
Salting, peppering, and hashing passwords
mCoding
x to bool conversion in Python, C++, and C
mCoding
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
Find the Skyline Problem with C++ Solution Explained
mCoding
The ONLY C keyword with no C++ equivalent
mCoding
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
Multiple Assignments in Python
mCoding
Why I don't like Python's chained comparisons
mCoding
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
You can pip install directly from GitHub
mCoding
__new__ vs __init__ in Python
mCoding
Metaclasses in Python
mCoding
The easy way to keep your repos tidy.
mCoding
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
Python __slots__ and object layout explained
mCoding
C++ cache locality and branch predictability
mCoding
Avoiding import loops in Python
mCoding
25 nooby Python habits you need to ditch
mCoding
Python staticmethod and classmethod
mCoding
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
31 nooby C++ habits you need to ditch
mCoding
Interviewing the creator of C++, Bjarne Stroustrup
mCoding
More on: RAG Basics
View skill →Related Reads
📰
📰
📰
📰
Azure AI Search in 2026, how to build a RAG pipeline
Dev.to · Carlos José Castro Galante
RAG local en .NET: Chatea con tu Documentación (sin nube, sin API keys)
Dev.to AI
Build a Local RAG in .NET: Chat With Your Docs (No Cloud, No API Keys)
Dev.to AI
What Is RAG? Or: How I Stopped Trusting My Chatbot’s Confidence
Medium · LLM
Chapters (5)
Intro
1:08
Keyword-only arguments
4:50
Positional-only arguments
7:45
Uncommon to use both
8:29
Speed test, position args are faster
🎓
Tutor Explanation
DeepCamp AI