Positional-only and keyword-only arguments in Python

  Рет қаралды 83,576

mCoding

mCoding

Күн бұрын

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 (mcoding.io)
Source code: github.com/mCodingLLC/VideosS...
Positional-only PEP: peps.python.org/pep-0570/
Keyword-only PEP: peps.python.org/pep-3102/
SUPPORT ME ⭐
---------------------------------------------------
Patreon: / mcoding
Paypal: www.paypal.com/donate/?hosted...
Other donations: mcoding.io/donate
Top patrons and donors: Jameson, Laura M, Dragos C, Vahnekie, John Martin, Casey G
BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Discord: / discord
Github: github.com/mCodingLLC/
Reddit: / mcoding
Facebook: / 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

Пікірлер: 190
@ethanevans8909
@ethanevans8909 2 жыл бұрын
Every video you drop is so hugely important. Youre single handedly saving my in-production code from ignorance
@mCoding
@mCoding 2 жыл бұрын
I take full credit! Unless anything goes wrong, then you did it all on your own!
@cobalius
@cobalius 2 жыл бұрын
Yes! I think the same about it!
@enisten
@enisten 2 жыл бұрын
@@mCoding Sounds like my boss.
@markcuello5
@markcuello5 2 жыл бұрын
Thanks; and I`m glad You`re happy.
@Y2B123
@Y2B123 Жыл бұрын
@@mCoding I think Trump stole your quote lol.
@matheusaugustodasilvasanto3171
@matheusaugustodasilvasanto3171 2 жыл бұрын
Wow. On other channels this video would just have been the display of the syntax and some code examples. But as always, you share valuable knowledge in the form of use cases, benchmarking, 'tricks' to remember the syntax, etc. I yearn to one day be as good of an educator as you. Thanks for the video!
@vladyslavkotov7570
@vladyslavkotov7570 2 жыл бұрын
What I love about these videos is that each highlights one specific topic that you rarely see anywhere else, yet all of them have real world applications. Thank you James
@mCoding
@mCoding 2 жыл бұрын
Thanks for the support!
@dsenese
@dsenese 2 жыл бұрын
That explanation was CLEAN! And the speed test was the icing on the cake! Thank you so much
@mCoding
@mCoding 2 жыл бұрын
Glad you enjoyed! I hope you find many other desserts on my channel.
@mrphlip
@mrphlip 2 жыл бұрын
One use-case I've heard for positional-only args is that it allows you to have a truly-general kwargs parameter. Like, say you had a function that lets you modify some sort of general-purpose configuration settings, and it needs to take two things as input: a section to put the settings in, and some key-value pairs for what settings to change. The definition could look like: def modify_config(section, **changes): ... and you'd then call this like: modify_config("subscriptions", mCoding=True) But what if you wanted to have a setting that is literally called "section"? You can't call: modify_coding("a thing", section="left") because it will treat the "section=" parameter as being the first arg to the function, not a part of the kwargs, and you'll get an error that you're providing two values for the same argument. So our function isn't completely general-purpose, we can't use it to change a setting that's called "section". However, what if we change that parameter to be positional-only? def modify_config(section, /, **changes): ... modify_config("a thing", section="left") Now, the call works properly, exactly as we'd expect it, and the section="left" parameter ends up in the kwargs.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 жыл бұрын
While your example works, I can’t help feeling it’s a little strained.
@shreyashchauhan6359
@shreyashchauhan6359 2 жыл бұрын
@@lawrencedoliveiro9104 strained how if may ask?
@leogama3422
@leogama3422 2 жыл бұрын
This is exactly what the dict() function does.(Even before the feature was added to the language, it was implemented as a special case in C)
@JorgeLuis-ts6qp
@JorgeLuis-ts6qp Жыл бұрын
In fact this is how Pablo Galindo Salgado justified the modification. The other option, let your function swallow everything, would have imply a horrible documentation. In addition this feature was already in use in the insights of the standard library. It just has become available for the Python users. As a fun fact the usage of the bar let the standard library implementation to be reduced in 3,000 lines.
@aaronm6675
@aaronm6675 2 жыл бұрын
Another engaging and informative video with a pleasantly narrow scope 🤠
@mCoding
@mCoding 2 жыл бұрын
Glad you enjoyed it!
@kyle-silver
@kyle-silver 2 жыл бұрын
When the positional only stuff came out, I also remember hearing that there were some reasons related to the C foreign function interface. Most other languages don’t have kwargs, and this (supposedly) helped maintain symmetry when you were defining wrappers for C functions
@mCoding
@mCoding 2 жыл бұрын
That would make sense, the default for wrapping a function in a language that doesn't have kwargs makes sense to be positional only.
@d00dEEE
@d00dEEE 2 жыл бұрын
Yeah, there have been positional-only built-ins forever, so when Argument Clinic was implemented, it supported them and the use of "/" (the "inverse" of "*") was adopted there. Then people started asking if they could write pure-Python functions with the same APIs as those in the built-ins, and the "/" was added to Python itself.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 жыл бұрын
That doesn’t make any sense. Keyword arguments allow Python to rearrange the arguments into the right order to pass to a lower-level function. The fact that the lower-level function is written in a language that doesn’t support keyword arguments is irrelevant, and no excuse for the higher-level language to limit itself.
@d00dEEE
@d00dEEE 2 жыл бұрын
@@lawrencedoliveiro9104 Well, Python didn't always have keyword arguments (I can't recall, but maybe added in 1.4 or 1.5?). At the time, creating keyword argument lists in the interpreter was quite expensive, so the already-existing builtins were left as positional-only, and that has been carried through history.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 жыл бұрын
@@d00dEEE Many existing functions have had keyword arguments added. By its nature, it doesn’t break backward compatibility.
@stevenluoma1268
@stevenluoma1268 Жыл бұрын
I recommend your videos all the time. The depth on a narrow topic is exactly the type of video I've been after lately. You dont just explain what it does and some examples, you show exactly how something works and you somehow do it concisely.
@wilcosec
@wilcosec Жыл бұрын
This is the most clear and concise explanation and how-to tutorial on python arguments I have seen. Excellent job. Bravo!
@mostafaseyedashor8768
@mostafaseyedashor8768 Жыл бұрын
one of the best explanation (about args and kwargs) i've ever heard
@rhtcguru
@rhtcguru 2 жыл бұрын
Great video. I recently came across your videos and have been gobbling them up and passing them along to my coworkers. Thank you so much for doing this and I really appreciate the nicely digestible length of your videos yum yum.
@mCoding
@mCoding 2 жыл бұрын
Haha gobble gobble. Enjoy! Glad you like my videos.
@Mx_Flix
@Mx_Flix Жыл бұрын
I learned an additional thing from this, as I didn't know about the {var_name=} feature of f-strings, so thank you for that as well!
@VojtechMach
@VojtechMach 2 жыл бұрын
You always provide a new (deeper) perspective on seemingly simple concepts. Im glad I found your channel, you have the best content Ive seen on YT.
@mCoding
@mCoding 2 жыл бұрын
Great to hear, your views are appreciated!
@fallingintime
@fallingintime Жыл бұрын
This has been in python since 3.0 and I never knew what it meant (have not seen it in many codebases with the exception of boto3 stubs) thanks for this!
@knut-olaihelgesen3608
@knut-olaihelgesen3608 2 жыл бұрын
Thank you so much. I've been wondering about the slash in function parameters for so long
@georgedicu7397
@georgedicu7397 2 жыл бұрын
Damn, man these videos are what I wanted, one the edge python cases/implementation or advanced video.
@CodingDragon04
@CodingDragon04 2 жыл бұрын
Had never known about this syntax, but I can think of some good usecases allready! Your video's are really the best for learning these obscure but very often usefull features you don't see in beginners courses.
@arbaazshafiq
@arbaazshafiq 2 жыл бұрын
Congrats on the 100k
@mCoding
@mCoding 2 жыл бұрын
Thank you so much 😀
@deeplearnit
@deeplearnit 2 жыл бұрын
I always learn something new from your videos, thank you!
@POINTS2
@POINTS2 2 жыл бұрын
I learned something new today. Thanks for making this video!
@sovietmaths5651
@sovietmaths5651 2 жыл бұрын
wow, just started learning about this. You're amazing, James.
@mCoding
@mCoding 2 жыл бұрын
Very welcome and thanks for watching!
@aliwelchoo
@aliwelchoo 2 жыл бұрын
Banging video. Learnt something new, seems advanced but simple to understand and use. Love it
@slava6105
@slava6105 2 жыл бұрын
Note that int.__pow__ (and maybe other number types) has "mod" parameter especially for cases "(x ** y) % mod"
@mCoding
@mCoding 2 жыл бұрын
Good catch! Thanks for pointing this out.
@mihai-gabriel-07
@mihai-gabriel-07 Жыл бұрын
Amazing video. I've actually never seen this feature used before but I feel like it should be best practice, especially when writing APIs
@christoferberruzchungata2722
@christoferberruzchungata2722 2 жыл бұрын
I learned this from the book “90 Specific Ways to Write Better Python”. It’s such a great book that I would recommend to anyone looking to become a more professional Python developer
@beto5720
@beto5720 2 жыл бұрын
Times I refactor my code before finding your channel = once, times I refactor my code after finding your channel = once a day
@ayyythatguy
@ayyythatguy 2 жыл бұрын
Such a useful video I wondered how to do this exact case yesterday by chance!!
@cafecafeliebe
@cafecafeliebe Жыл бұрын
Star is like star-args but without the args 🤣 mCoding is like m but with Coding 😄 Your content is so advanced, I love it! 👌
@fartzy
@fartzy Жыл бұрын
Amazing stuff as always my good man
@cyber-dioxide
@cyber-dioxide 2 жыл бұрын
Your channel booted up my python skills x10 🥂
@diamonddemon7612
@diamonddemon7612 2 жыл бұрын
This is EXACTLY what I need today!
@mohammadrezakarimi8180
@mohammadrezakarimi8180 2 жыл бұрын
Loved the "yum"! Also, James, where is your face? It was so nice to see you narrating the video :) Great work. Really appreciate your efforts.
@diegomountain7177
@diegomountain7177 Жыл бұрын
This was super informative. I understand a little better how to use *args and **kwargs which I know wasn't the point of this video. But still, this was very useful. Thank you!
@hupa1a
@hupa1a 2 жыл бұрын
Very interesting insights Thank you for that video!
@joseville
@joseville Жыл бұрын
5:05 best part! 0:40 jfyi for the completionist foo(2, a=1, c=3) is a TypeError foo() got multiple values for argument 'a'
@justingerber9531
@justingerber9531 2 жыл бұрын
Awesome video! I like the def foo(*, arg_1, arg_2, arg_3=default_3, ...): pattern to force users to explicitly pass in keyword names. This is useful for methods that have a lot of inputs to a) force users to look up the signature so they see everything that they need to pass and are able to pass in and b) ensure no parameter mix ups occur. This approach also makes code a bit more explicit which can be helpful. Of course it's more verbose which could be seen as a downside. It would be nice to see examples where you include default arguments as well. When I first learned about these I was confused by the fact that there was a difference between keyword only args and optional args (before I erroneously thought they were one and the same). I also think there's a confusing case of: Can I have position-only args with and without defaults while also having keyword-only args with and without defaults? I don't really need to see examples where there are explicitly positional or keyword args because I feel like those cases are just confusing, and like you helpfully pointed out, not really useful. I do have to say that I've hesitated to put these patterns in much of my code though, because I believe it's python 3.9+ and at the time I learned it I was still working with lower versions of python. I also hesitate to put it in because I think most people don't know what it means and it would surprise them.
@leogama3422
@leogama3422 2 жыл бұрын
The positional-only feature is recent, but the "/" syntax has been used in the built-in functions' documentation for a long time
@MrSteini124
@MrSteini124 2 жыл бұрын
Wonderful! Great as always
@turbine1
@turbine1 2 жыл бұрын
So good. Never heard about it the pure * before and directly implemented it in my code
@suvajitmitra58
@suvajitmitra58 9 ай бұрын
great explanation! thanks!!
@n49o7
@n49o7 2 жыл бұрын
My takeaway: star yum star star yum yum slash NO NAME FOR YOU Great vid !
@JoQeZzZ
@JoQeZzZ Жыл бұрын
I never knew about plain *, it makes total sense.
@Epinardscaramel
@Epinardscaramel Жыл бұрын
Oh that looks great! I have to use it in the library I'm writing
@sharpfang
@sharpfang Жыл бұрын
I worked with a (proprietary) PHP framework which had an approach of making as few args as possible mandatory, and as many parameters of an operation args with sensible defaults. The "keyword arguments" was the way it was implemented - you'd often have a function with 15 args, one required, the rest - as needed. It was very friendly in use that way - bare minimum to get it to work, easy to change whatever you want changed.
@GanerRL
@GanerRL 2 жыл бұрын
I somehow have never see this syntax. I've seen mentions of this while manipulating python ASTs but I didn't know what they really meant lol
@GanerRL
@GanerRL 2 жыл бұрын
@@mrdkaaa you read the docs? nerd
@pranavnyavanandi9710
@pranavnyavanandi9710 2 жыл бұрын
What does ASTs mean?
@GanerRL
@GanerRL 2 жыл бұрын
@@pranavnyavanandi9710 abstract syntax tree, basically I was modding python to make creating and manipulating lambdas easier lol
@denissetiawan3645
@denissetiawan3645 2 жыл бұрын
superb explanation
@user-mt7pq9bq9w
@user-mt7pq9bq9w 2 жыл бұрын
Very helpful !😀
@MCKBURNHOUSE
@MCKBURNHOUSE 2 жыл бұрын
This is GOLD!
@robertbrummayer4908
@robertbrummayer4908 2 жыл бұрын
Great and interesting video
@parsasalavati1006
@parsasalavati1006 2 жыл бұрын
Great videos! ✌ Could you do an in-depth video on asyncio? By in-depth I mean how it works under the hood; Particularly how it compares to & differs from multithreading, how does python know when to "wait for this to finish and run some other code in the meantime" and what happens under the hood when the results are ready and how it relates to OS scheduling and sleep queue. So basically, content that you find on this channel that it's harder to find elsewhere.
@mCoding
@mCoding 2 жыл бұрын
This has been on my list for a long time!
@PanduPoluan
@PanduPoluan Жыл бұрын
Lukasz Langa had made a series of videos if you really want a deep dive into asyncio: kzfaq.info/sun/PLhNSoGM2ik6SIkVGXWBwerucXjgP1rHmB
@JoseHenrique-xg1lp
@JoseHenrique-xg1lp Жыл бұрын
The benchmark at the end was the icing on the cake. Is there a performance change? Not enough to bother, but at least we know that
@joffreybluthe7906
@joffreybluthe7906 2 жыл бұрын
Great content once more!
@Techiesse
@Techiesse 2 жыл бұрын
Awesome! Props to you.
@kotslike
@kotslike 2 жыл бұрын
Amazing!
@collinahn
@collinahn 2 жыл бұрын
thanks for the video
@RedBearAK
@RedBearAK Жыл бұрын
OMG, I had to have a “dummy” parameter as the first argument because I couldn’t find a simple way to force all parameters to be named. Never found this syntax of just star-comma offered as a solution. It’s quite logical to remember that it’s like “*args” without the argument name. As if it just doesn’t give anywhere for the positional args to go.
@sadhlife
@sadhlife 2 жыл бұрын
4:00 this is also why most projects should probably use mypy and type annotations :)
@salahjaabari8931
@salahjaabari8931 2 жыл бұрын
I love your videos ❤️
@mCoding
@mCoding 2 жыл бұрын
Thanks so much!
@Khushpich
@Khushpich 2 жыл бұрын
Thanks James, great video. In what python version of python was this added?
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 жыл бұрын
Keyword-only arguments were introduced in 3.0.
@sadhlife
@sadhlife 2 жыл бұрын
positional only was 3.8
@Yotanido
@Yotanido Жыл бұрын
I've defined keyword-only parameters before, but I honestly had no idea positional-only existed. Doubt I'll find much use for it, but good to know.
@xan1716
@xan1716 2 жыл бұрын
This I find helpful when there're a lot of boolean args, which if passed without keywords, would make its invocation harder to understand -- e.g. `process_two_numbers(3, 5, True, True, False, None, True)` -- no idea what's happening here without forced kwargs :)
@MrFibbanacci
@MrFibbanacci Жыл бұрын
U can memorize /* which start multiline comment in if I remember correct. You are welcome! : )
@PhoenixClank
@PhoenixClank Жыл бұрын
Until now I haven't used this feature a lot because I don't want to put restrictions on the users of my code. However, I make most boolean arguments keyword-only, because when passed as a literal it's usually not clear from reading the code what the argument is supposed to mean.
@SkrtlIl
@SkrtlIl 2 жыл бұрын
Is power mod slow because you could also implement binary exponentiation together with taking the mod on the output on each iteration?
@mCoding
@mCoding 2 жыл бұрын
Yes exactly, fast pow and take mod n each iteration will be much much faster then computing a huge exponentiation then reducing mod n.
@arisweedler4703
@arisweedler4703 2 жыл бұрын
I love it. I want to feed the YT algorithm so I make this comment.
@hamzasayyid8152
@hamzasayyid8152 2 жыл бұрын
Never seen this before. So cool. I wonder why positional only is faster than keyword. Thought it would be backwards
@lunarmagpie4305
@lunarmagpie4305 2 жыл бұрын
I think its because keyword arguments are stored as a dict and positional arguments are a tuple. A dict is a considerably more expensive data structure.
@RemotHuman
@RemotHuman Жыл бұрын
The best part of this is f"{x=}" I didnt know you could do that
@clementlelievre4600
@clementlelievre4600 Жыл бұрын
thanks for the good content
@mCoding
@mCoding Жыл бұрын
You are very welcome, glad you enjoyed!
@clementlelievre4600
@clementlelievre4600 Жыл бұрын
@@mCoding in my IDE I have an extension that pre-writes docstrings for me, based on the parsing of the function body and signature, but it does not capture * and / in this context. I made a feature request ;)
@trag1czny
@trag1czny 2 жыл бұрын
great vid as always btw discord gang 🤙🤙
@jacanchaplais8083
@jacanchaplais8083 2 жыл бұрын
the video is 9 minutes long and only uploaded 2 minutes ago 🤔
@user-pl6hc4kj1o
@user-pl6hc4kj1o 2 жыл бұрын
4x speed?
@trag1czny
@trag1czny 2 жыл бұрын
@@jacanchaplais8083 I had access to it before publication as a moderator
@jacanchaplais8083
@jacanchaplais8083 2 жыл бұрын
@@trag1czny fair haha
@mCoding
@mCoding 2 жыл бұрын
Thank you for your loyal viewing!
@ragingroosevelt
@ragingroosevelt 2 жыл бұрын
How did you run into all this information? I consider myself to be a reasonably experienced Python dev and I swear, 75% of your videos I come away learning something that I can actually use in my day-to-day work in a way that makes my output unquestionably better. What can I do to rapidly pick up info like this?
@sadhlife
@sadhlife 2 жыл бұрын
books: fluent python and python cookbook taught me soo much about python that I'd probably not have learned anywhere else reading library code really helps. especially libraries that were written by well known python core devs very recently. good examples would be fastapi for example, you'll learn a whole lot about type annotations lastly, python's own tutorial covers pretty much every language feature. I take a look at it every few months
@sadhlife
@sadhlife 2 жыл бұрын
fluent python has a 2nd edition coming out in May, that's going to be one of the best Python resources for a while
@ragingroosevelt
@ragingroosevelt 2 жыл бұрын
@@sadhlife I just started using FastAPI so that would be especially relevant. I've read a few libraries code before but that was just because they were very poorly documented and I was trying to figure out how to do something. Reading through on well-documented libraries seems like a good idea. Thanks!
@baudneo
@baudneo 2 жыл бұрын
Yeah boi!
@XcaliburKurosaki
@XcaliburKurosaki 2 жыл бұрын
"We don't need x." I feel attacked lmao Jokes aside, this has been an awesome watch with some immediate gains in my codebases 🥰
@JonDoe-oy8bt
@JonDoe-oy8bt 2 жыл бұрын
4:58. If you want to swallow up keyword args you can just use **kwargs. This isn't exactly a parallel to / but is the equivalent kwargs version of *args
@grunklestanlee2774
@grunklestanlee2774 2 жыл бұрын
I’ve actually used this before without really knowing what it was doing while making a discord bot
@XCanG
@XCanG 2 жыл бұрын
7:22 Your note about slow function, what would be faster equivalent?
@mCoding
@mCoding 2 жыл бұрын
In the algorithm to compute pow, which is typically some kind of repeated squaring algorithm, take mod n each step instead of at the end. The builtin pow function also takes a mod parametee that does this.
@walkdead94
@walkdead94 2 жыл бұрын
I always wanted to know whataheck that * meant on the others code... dam.. thank you.. that was greatly useful!
@MrTyty527
@MrTyty527 2 жыл бұрын
I think I finally remember the syntax... the / * is really hard to remember
@Talon_24
@Talon_24 2 жыл бұрын
My usual examples for why you would want keyword/positional-only arguments are: Keyword Only: consider n_sorted(data, true) -- what does the 'true' set there? ascending/descending? nulls first/last? Maybe something else? What if you would find n_sorted(data, false, true) -- which true and false is which? is the first false only there to keep the second argument as default to reach the third positional argument? n_sorted(data, nulls_last=True) is unambiguous about that. Positional only: Reason to enforce positional order could be if the ability to change the order would only exist to mess with the person reading the code. Similar to your example, divide(y=2, x=3) or Fraction(denominator=2, numerator=3) would seem to be only there to obfuscate that this is 3/2 and not 2/3
@KappakIaus
@KappakIaus 2 жыл бұрын
But why not just leave the caller the option? In the first case, they can still use keyword arguments if they feel like the ambiguity might be a problem. Same thing in the 2nd example. If the caller decides to swap the argument order, they probably had a good reason for it. Basically, you are trying to force the person using your code to do what you think is best for them. But by doing so, you are blocking off use-cases you might not have thought about.
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 жыл бұрын
Keyword-only arguments can be useful where you think you might add more later, and maybe change the order. There is one situation where there is a specific use for them: normally once you specify a default value for a formal argument, all remaining ones must also have defaults. But in the keyword-only section, this rule no longer applies, and you can omit the default for an arg that comes after one that has a default.
@bettercalldelta
@bettercalldelta 2 жыл бұрын
7:43 I actually recently used that in my project lol
@codingcrashkurse6429
@codingcrashkurse6429 2 жыл бұрын
Saw this some weeks ago in a colleagues Code.
@Hyrtsi
@Hyrtsi Жыл бұрын
I've always wondered what **kwargs means but never bothered to look up. Thanks!
@Xavier-es4gi
@Xavier-es4gi 2 жыл бұрын
This is not related to the video but since there are probably many python expert here I'll ask my question. Can I have some tips/good practices about how to create and organize a python package. Also what should be favored, relative or absolute imports? I prefer absolute because theye are easy to copy paste between files.
@ludo3941
@ludo3941 2 жыл бұрын
Pretty interesting
@PhyFlame
@PhyFlame 2 жыл бұрын
I never knew about the '/' and '*' in the function parameter list - they are awesome. Also, I realised that I can cheat the "slap the like button an odd number of times" system by hitting it twice, but also clicking dislike once in between. Under the cost of the emotional baring of having your video disliked for a moment this still results in a like ;)
@junkokonno
@junkokonno Жыл бұрын
you love to see it
@quintencabo
@quintencabo 2 жыл бұрын
You should be able to put the star next to the slash if you don't need the middle
@bzboii
@bzboii 2 жыл бұрын
How does this work w partial application?
@maartenofbelgium
@maartenofbelgium 2 жыл бұрын
4:35 Buying 10,000 items of $4,500 each, costs as much as buying 4,500 items of $10,000 each. Unless you're the seller :)
@mCoding
@mCoding 2 жыл бұрын
I think you'll find the buyer would be much happier to receive 10000 units rather than 4500 units for the same price! (Assuming there aren't any crazy storage costs, minimum holding times, or other penalties incurred for holding units).
@maartenofbelgium
@maartenofbelgium 2 жыл бұрын
@@mCoding These are no bugs, just happy mistakes.
@ali-om4uv
@ali-om4uv 2 жыл бұрын
I have rhe impression you are probably resonably decent at writing python code :-)
@AsgerJon
@AsgerJon 2 жыл бұрын
What is the "good practice" way of implementing keyword arguments with default values?
@user-xh9pu2wj6b
@user-xh9pu2wj6b 2 жыл бұрын
something like def f(x=None): if x is None: x = smth That is unless you also plan to allow for None as a valid value, then it's a bit more complicated
@AsgerJon
@AsgerJon 2 жыл бұрын
@@user-xh9pu2wj6b So it's actually the same as for a positional argument? What I am doing now is to have a default dictionary, I loop through its keys, if the key is in kwargs.keys(), I replace the default value with kwargs[key]. This feels... too javascripty, i don't know. The reason I prefer something like this that I would like to have a function taking an arbitrary kwargs dictionary with an arbitrary default value dictionary.
@user-xh9pu2wj6b
@user-xh9pu2wj6b 2 жыл бұрын
@@AsgerJon oh, in case of multiple defaults in a dictionary like that, I think it's a fine approach. I code in TS/JS a lot, so I don't see any real problem there) Another way to do it is to use an update method of a dictionary and pass kwargs in it. You'll have something like: def f (**kwargs): kvals={"x": 1, "y": 2} kvals.update(kwargs) This will essentially merge the two dicts with overwrites, so if some key was only in kvals, it'll stay there with default value. If it's in both dicts, the value will come from kwargs. And I think it might be faster than looping by hand, but I never measured the performance.
@AsgerJon
@AsgerJon 2 жыл бұрын
​@@user-xh9pu2wj6b Speed is no concern ever in Python. If part of your code for real causes speed issues, then numba.jit and possibly even cuda jit. Here's what I'll do: I will subclass the default dictionary, into one that does as you suggest, but then I will put it in the __add__ method. Like: self.defVals = {...} self.defVals += kwargs BOOM! Python all the way!
@ThankYouESM
@ThankYouESM 2 жыл бұрын
I now very much want to know how to make a Python3-Thinter-to-HTML5 app far as it can get... because I very much struggle many thousands of times more with every other programming language despite the 6 years I tried. Granted... p5js has recently got my attention, but... it still looks a bit overly complicated to re-edit which I accomplished very much the same graphics which is too slow and doesn't transfer to Android via fully* the SD card. Unfortunately... I can't even find an entire side-by-side syntax comparison.
@markcuello5
@markcuello5 2 жыл бұрын
`mCoding` seems like A/M`tion; similar to `Playwright`.
@args4488
@args4488 2 жыл бұрын
yum
@lawrencedoliveiro9104
@lawrencedoliveiro9104 2 жыл бұрын
6:24 How about “truthvalue” or “flag”. Or even “colbert”.
@glass-ships
@glass-ships Жыл бұрын
This isn't really important but.. 10,000x4500 and 4500x10,000 are the same since multiplication is commutative. Awesome video as always though!
@matt566
@matt566 2 жыл бұрын
Wouldn’t it make sense from an enterprise standpoint that all arguments are passed as keywords? Otherwise the reader has to reference the functions implementation or comments if it has them to understand what the parameters mean.
@jullien191
@jullien191 2 жыл бұрын
Il y a grep sur Windows?
@mCoding
@mCoding 2 жыл бұрын
WSL
@jenaf3760
@jenaf3760 2 жыл бұрын
damn I envy people who can work with python. I work on an ancient mutated php codebase. I recently found some functions with a messy signsture and a bunch of option paramters. That kind of stuff is just bad code in php. In python that might work If I used the method to force those arguments to be keyword only. (in other places the codebase expects (what php calls) an "array" with keyword=>value pairs wich basically simulates keyword only args. fun times.
@merthyr1831
@merthyr1831 2 жыл бұрын
Being a dart developer where the convention is to use keyword arguments over positional ones, I wish more languages used that convention too! Makes reading others code a LOT easier when you don't have to learn the order of arguments in a function. Dart has extra features to make keyword args easier to use too (such as automatically filling backed fields) but definitely a feature you should use in other languages too!!
@Zifox20
@Zifox20 2 жыл бұрын
@MithicSpirit
@MithicSpirit 2 жыл бұрын
Discord gang
@mCoding
@mCoding 2 жыл бұрын
Always a pleasure!
8 things in Python you didn't realize are descriptors
14:21
Python's most DISLIKED __dunder__ (and what to use instead)
9:59
Each found a feeling.#Short #Officer Rabbit #angel
00:17
兔子警官
Рет қаралды 6 МЛН
DELETE TOXICITY = 5 LEGENDARY STARR DROPS!
02:20
Brawl Stars
Рет қаралды 15 МЛН
Async for loops in Python
16:36
mCoding
Рет қаралды 57 М.
Что за звери *args и **kwargs
38:02
Python Russian
Рет қаралды 7 М.
You Can Do Really Cool Things With Functions In Python
19:47
ArjanCodes
Рет қаралды 216 М.
5 Useful Dunder Methods In Python
16:10
Indently
Рет қаралды 51 М.
Python lists remember what you did to them
10:04
mCoding
Рет қаралды 127 М.
ARRAYLIST VS LINKEDLIST
21:20
Core Dumped
Рет қаралды 49 М.
"TypedDict" In Python Is Actually AWESOME!
7:32
Indently
Рет қаралды 28 М.
CONCURRENCY IS NOT WHAT YOU THINK
16:59
Core Dumped
Рет қаралды 85 М.
super/MRO, Python's most misunderstood feature.
21:07
mCoding
Рет қаралды 212 М.
iPhone 15 Unboxing Paper diy
0:57
Cute Fay
Рет қаралды 3,6 МЛН
APPLE совершила РЕВОЛЮЦИЮ!
0:39
ÉЖИ АКСЁНОВ
Рет қаралды 359 М.
Где раздвижные смартфоны ?
0:49
Не шарю!
Рет қаралды 807 М.
Will the battery emit smoke if it rotates rapidly?
0:11
Meaningful Cartoons 183
Рет қаралды 9 МЛН