Positional-only and keyword-only arguments in Python

mCoding · Beginner ·🔍 RAG & Vector Search ·4y ago
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 Goodbye, List! Type hinting standard collections - New in Python 3.9
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
2 Python's comma equals ,= operator?
Python's comma equals ,= operator?
mCoding
3 Finding Primes in Python with the Sieve of Eratosthenes
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
4 Find the First Missing Positive Int | Hard Interview Question on LeetCode
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
5 JSON Tutorial Python | Basic Python Recipes
JSON Tutorial Python | Basic Python Recipes
mCoding
6 Simulating Brownian Motion in Python
Simulating Brownian Motion in Python
mCoding
7 The Single Most Useful Decorator in Python
The Single Most Useful Decorator in Python
mCoding
8 The Fastest Way to Loop in Python - An Unfortunate Truth
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
9 Numpy Array Broadcasting In Python Explained
Numpy Array Broadcasting In Python Explained
mCoding
10 Brownian Motion Single Path Zoom
Brownian Motion Single Path Zoom
mCoding
11 Brownian Motion Fractal Zoom
Brownian Motion Fractal Zoom
mCoding
12 Magic Methods - Making Python builtins work with your classes
Magic Methods - Making Python builtins work with your classes
mCoding
13 50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
14 The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
15 How Fast is Python's Sort? Performance Testing
How Fast is Python's Sort? Performance Testing
mCoding
16 C++ First Missing Int, faster than 100%!
C++ First Missing Int, faster than 100%!
mCoding
17 [April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
18 Python dataclasses will save you HOURS, also featuring attrs
Python dataclasses will save you HOURS, also featuring attrs
mCoding
19 C++ Sudoku Solver in 7 minutes using Recursive Backtracking
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
20 Every PROOF you've seen that .999... = 1 is WRONG
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
21 Python's sharpest corner is ... plus equals? (+=)
Python's sharpest corner is ... plus equals? (+=)
mCoding
22 Binary Search - A Different Perspective | Python Algorithms
Binary Search - A Different Perspective | Python Algorithms
mCoding
23 The Best Way to Check for Optional Arguments in Python
The Best Way to Check for Optional Arguments in Python
mCoding
24 Local and Global Variable Lookup Weirdness in Python
Local and Global Variable Lookup Weirdness in Python
mCoding
25 Efficient Exponentiation
Efficient Exponentiation
mCoding
26 How To Install Python for Data Science
How To Install Python for Data Science
mCoding
27 0.1 + 0.2 is NOT 0.3 in Most Programming Languages
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
28 Python 3.10's new type hinting features
Python 3.10's new type hinting features
mCoding
29 Python 3.10's Quality of Life improvements
Python 3.10's Quality of Life improvements
mCoding
30 Introducing mZips! Python Zip and Zip Longest
Introducing mZips! Python Zip and Zip Longest
mCoding
31 Match statement tips
Match statement tips
mCoding
32 Using except: is a HUGE mistake
Using except: is a HUGE mistake
mCoding
33 Python + YouTube API | Automating descriptions
Python + YouTube API | Automating descriptions
mCoding
34 Anaphones, phonetic anagrams
Anaphones, phonetic anagrams
mCoding
35 Cracking passwords using ONLY response times | Secure Python
Cracking passwords using ONLY response times | Secure Python
mCoding
36 Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
37 Diagnose slow Python code. (Feat. async/await)
Diagnose slow Python code. (Feat. async/await)
mCoding
38 Python MD5 implementation
Python MD5 implementation
mCoding
39 Salting, peppering, and hashing passwords
Salting, peppering, and hashing passwords
mCoding
40 x to bool conversion in Python, C++, and C
x to bool conversion in Python, C++, and C
mCoding
41 You should put this in all your Python scripts | if __name__ == '__main__': ...
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
42 Find the Skyline Problem with C++ Solution Explained
Find the Skyline Problem with C++ Solution Explained
mCoding
43 The ONLY C keyword with no C++ equivalent
The ONLY C keyword with no C++ equivalent
mCoding
44 Should you use "not not x" instead of "bool(x)" in Python? (NO!)
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
45 Multiple Assignments in Python
Multiple Assignments in Python
mCoding
46 Why I don't like Python's chained comparisons
Why I don't like Python's chained comparisons
mCoding
47 Automated Testing in Python with pytest, tox, and GitHub Actions
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
48 You can pip install directly from GitHub
You can pip install directly from GitHub
mCoding
49 __new__ vs __init__ in Python
__new__ vs __init__ in Python
mCoding
50 Metaclasses in Python
Metaclasses in Python
mCoding
51 The easy way to keep your repos tidy.
The easy way to keep your repos tidy.
mCoding
52 Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
53 Python __slots__ and object layout explained
Python __slots__ and object layout explained
mCoding
54 C++ cache locality and branch predictability
C++ cache locality and branch predictability
mCoding
55 Avoiding import loops in Python
Avoiding import loops in Python
mCoding
56 25 nooby Python habits you need to ditch
25 nooby Python habits you need to ditch
mCoding
57 Python staticmethod and classmethod
Python staticmethod and classmethod
mCoding
58 Building a Python app with Anvil to email me if my website goes down (includes paid features)
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
59 31 nooby C++ habits you need to ditch
31 nooby C++ habits you need to ditch
mCoding
60 Interviewing the creator of C++, Bjarne Stroustrup
Interviewing the creator of C++, Bjarne Stroustrup
mCoding

This video teaches how to define positional-only and keyword-only arguments in Python, with examples and use cases, and discusses the performance implications of each.

Key Takeaways
  1. Define a function with positional-only arguments using a star (*) after the parameter name
  2. Define a function with keyword-only arguments using a star (*) after the parameter name
  3. Use a slash at the end of the argument list to force all arguments to be positional-only
  4. Use a slash directly followed by a star to force all arguments to be either positional-only or keyword-only
  5. Pass positional-only arguments before the slash in the argument list
  6. Pass keyword-only arguments after the slash in the argument list
  7. Create a normal function with three regular parameters
  8. Call the function with positional, keyword, and mixed arguments
  9. Redefine the function to make everything positional-only and time it
  10. Redefine the function to make everything keyword-only and time it
💡 Positional-only and keyword-only arguments can be used to improve code readability and performance by forcing specific argument ordering and reducing the overhead of keyword argument lookup.

Related Reads

📰
Azure AI Search in 2026, how to build a RAG pipeline
Learn to build a RAG pipeline using Azure AI Search in 2026 and improve your information retrieval capabilities
Dev.to · Carlos José Castro Galante
📰
RAG local en .NET: Chatea con tu Documentación (sin nube, sin API keys)
Learn to implement RAG locally in .NET without relying on cloud services or API keys, enabling you to chat with your documentation
Dev.to AI
📰
Build a Local RAG in .NET: Chat With Your Docs (No Cloud, No API Keys)
Learn to build a local RAG in .NET to chat with your documents without relying on cloud services or API keys
Dev.to AI
📰
What Is RAG? Or: How I Stopped Trusting My Chatbot’s Confidence
Learn about RAG and how it can improve chatbot confidence by retrieving relevant information from a database to support its answers
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
Up next
Deploying a Retrieval-Augmented Generation (RAG) in AWS Lambda
Abonia Sojasingarayar
Watch →