11 ms·
Strict Python function parameters
- amelius 5y ago"Strictness" means something else in language design. https://en.wikipedia.org/wiki/Evaluation_strategy https://en.wikipedia.org/wiki/Evaluation_strategy
- dundarious 5y agoPython is already strictly evaluated. It's not ambiguous in that way.
- amelius 5y agoTitle made me wonder if they changed it or added a new feature around it.
- Tyr42 5y agoI was curious if they meant strict evaluation, but I clicked through and it was an interesting argument about being strict with what you accept.
- bmn__ 5y agoThat's a misnomer and I'm glad it's already getting fixed in some places: the newer, better word is "eager". This frees up "strict".
- hprotagonist 5y agoi am a huge fan of this style: def foo(obvious_thing:type, *, modifier:type, modifier2:type, …) Because I find this call incomprehensible: foo(items, 12, “apple”) and this immediately better: foo(items, num=12, kind=“apple”) and preventing my callers from being able to do the first is a huge win.
- peteradio 5y agoSeems reasonable but when are you actually calling foo like: foo(items, num=12, kind=“apple”) vs: foo(items, num=num, kind=kind) ? Then you might as well get your info from the variable names in the calling method.
- messe 5y agoThere's been some discussion on that[1], with some suggesting the introduction of syntax analogous to f-strings: foo(items, num=, kind=) # equivalent to foo(items, num=num, kind=kind) But as far as I know there hasn't been a formal proposal (I could be wrong, and am happy to be corrected on this). [1]: https://lwn.net/Articles/818129/ https://lwn.net/Articles/818129/
- hprotagonist 5y agothat looks nice! not essential, but nice. I like the similar 3.8+ f-string improvement: x=5 print(f”{x=}”)
- hprotagonist 5y agoand one day someone goofs and foo(items, kind, num) and then everyone is sad again.
- wheelerof4te 5y agoYes, but keyword arguments are a good fallback option. They indicate that you are indeed passing the required arguments. So, the def foo(val, querry=querry): ... doesn't look as funny as you might think.
- DangitBobby 5y agoForcing your consumers to use a style you like is not a "win", it's a power play.
- jackblemming 5y ago
- rytill 5y agoThank you for sharing. I wish this were the default behavior of positional and keyword arguments rather than requiring a `/, *` in every function definition.
- eatonphil 5y agoI always strongly encourage Python programmers to start flipping through Effective Python to see more like this (I believe it includes this tip as well). Great book covering parts of the language and stdlib you may not remember or may not have heard of.
- softwaredoug 5y agoI'm curious if anyones found a good solution to Python default args? For example, this doesn't do what people expect: def foo(bar=Bar()) ... Because this creates exactly one Bar at function definition time, not a Bar per function call. Instead what people usually want is: def foo(bar=None) if bar is None: bar = Bar() ... I hate having to have a block of `if bar is None` at the top of my functions. I wonder if there's a library that helps make creating functions with default args easier? Or any tips people have?
- hultner 5y agoThere’s a PEP suggested for 3.11 handling this https://www.python.org/dev/peps/pep-0671/ https://www.python.org/dev/peps/pep-0671/
- meowface 5y agoSounds like a good idea. Not really a fan of the suggested syntax, though: def fn(s, n=>len(s)): "=>" just kind of bugs me, for some reason. (I love me some bikeshedding.) Of the alternatives they offer, ":=" kind of looks nicest to me: def fn(s, n:=len(s)): Though it doesn't really line up with the semantics of the existing walrus operator. Also, as the PEP mentions, it could look confusing when mixed with type annotations. Semantically, the "?=" alternative might be best, since it kind of makes it clear it's a default, and doesn't conflict with anything else in the language: def fn(s, n?=len(s)): Kind of reads like "present? else = ...". edit: At this point I'd shift from "might be best" to "almost certainly is best". I'm now a zealous "?=" advocate.
- kortex 5y agoI agree. I think python needs some solution to the `def foo(mylist=[])` which is a mistake I see devs make all the time. `foo=>func(a)` is awful. There's too much precedent that `x = f => {}` defines a lambda with x as a parameter. This flips it on its head. `@` would be challenging for the parser. `:=` also does not match the walrus semantics. `x ?= default` is perfect IMHO. There's already prior art (Makefiles) that this means exactly "present? else = ..." with lazy evaluation of RHS expression. It also would allow eliminating the "if x is SENTINEL" pattern, where None is a valid non-default argument.
- nmalaguti 5y agoWhile this is nice in a lot of ways, it also can make it harder for your callers to use more dynamic patterns. You can no longer call it with process_data(**kwargs) and have the data field pulled out of kwargs. Of course you can still do data = kwargs.pop(“data”) process_data(data, **kwargs) but if you are the only library doing it, it can cause things to break when it breaks programmers expectations.
- masklinn 5y agoNot sure that's an issue, since the parameter does not have a name. Just call it as `*args, **kwargs`. That's something you need to do when forwarding anyway.
- IshKebab 5y agoThat's a good thing! Using `kwargs` is generally a terrible idea.
- DangitBobby 5y agoPlease elaborate.
- spicybright 5y agoIt's impossible to see what arguments a function expects without reading all the code that uses it. You can't always trust documentation to be accurate and up to date.
- edgyquant 5y agoIn a dynamic language it’s already hard enough determine what type a given variable is at runtime once the codebase reaches a certain size. When you’re passing arbitrary parameters in the form of kwargs that just adds another layer of dynamism on top that can make debugging even more difficult. It definitely has its place but it’s generally a good idea to use positional parameters if you know they will be passed.
- SethMLarson 5y ago
- Zababa 5y agoThe "encoding" argument seems like the perfect use case for a strict type, ideally something that works like a sum type, or union types in TS. I think the difference is that in Python unions are unions of types, and not of values. I think "typing.Literal" would be what you can use here in Python.
- joshuamorton 5y agoDepending on the approach that can work, although there are cases where trying to making encoding a literal would be too restrictive (imagine a system that dynamically loads parser plugins, which isn't as uncommon as it sounds), so a literal restricted to ascii and utf-8 would prevent someone from parsing latin-1 or idk, protobuf bytes.
- Zababa 5y agoThat's a good point. I can see it working with static typing by being more liberal in what you accept as enconding, and accepting a validation function that would take the type of the encoding (for example string) and returning a boolean. But you're right, the type itself of the encoding will have to be wider.
- dec0dedab0de 5y agoI really don't like the idea of a function forcing me to use it a specific way. It's the same reason I don't like type checking at runtime. I can see the benefit of forcing junior members of my team to use keyword arguments, but I would be so annoyed if a library author did it to me. Unless there is a technical reason, your callables should just work the same way as all the others. I can't think of any reason to use positional only arguments, but keyword only arguments would be nice if I had a variable length of positional arguments that get packed, but then wanted to have an optional argument to change some behavior. But even then it's normally better to just have the caller send an iterable.
- DangitBobby 5y agoAgreed. This makes some patterns unnecessarily difficult for little gain. I wish they hadn't added these parameter restrictions to the language.
- toyg 5y agoThe creation of /, iirc, was initially meant strictly as a way of internally enforcing constraints when interfacing with C libraries. It just so happened that someone dug it out and went "what is this?" and then core devs agreed that it should be surfaced and officially supported. Personally, I find * useful and / fugly - because positional parameters are very opaque when reading code. They also don't give a chance to the IDE to guess what each parameter is meant for.
- rlayton2 5y agoI'm not a big fan of them either. For teaching beginners, its often "look at the help for this function, but ignore these bits for now", which is quite jarring. They are useful, but I think sometimes the advanced features run into the basic interfaces a bit, making it weirdly tricky to teach beginners without being confused.
- Siira 5y agoIgnoring them is pretty easy. The beginners should learn the art of selective attention anyway.
- nyellin 5y agoSlightly off-topic, but everyone writing modern Python should be familiar with Pydantic and similar libraries that use type hints for validation and parsing: https://pydantic-docs.helpmanual.io/ https://pydantic-docs.helpmanual.io/ https://fastapi.tiangolo.com/ https://fastapi.tiangolo.com/ https://github.com/tiangolo/typer https://github.com/tiangolo/typer We're using Pydantic for Robusta (https://github.com/robusta-dev/robusta https://github.com/robusta-dev/robusta) and absolutely love it. You get the best of traditional Python (rapid prototyping and no boilerplate) while still being able to scale your codebase and keep it maintainable. Robusta is the first large project I've written in Python where I'm not encountering type errors at runtime left and right.
- tempest_ 5y agoWe are using FastAPI a bit and it has been a decent experience. One thing to note about it is tiangolo is pretty content to maintain singular control over his projects which means the project only really advances when he has the time or interest to work on that specific project.
- nyellin 5y agoInteresting, thanks. I hadn't thought of that aspect.
- BeefySwain 5y ago> One thing to note about it is tiangolo is pretty content to maintain singular control over his projects which means the project only really advances when he has the time or interest to work on that specific project. Yes, he recently responded to some criticism of this basically saying that he has no real intention to increase the bus factor or permit more community control to his projects, which is obviously his right, but is also something that people should consider when deciding whether or not to go with them.
- wheelerof4te 5y agoNot everyone is using Pydantic (nor do I see the reason to) or even type hints, for that matter. Type hints are great when combined with a good IDE such as Pycharm, but are otherwise useless for Python. Sometimes, they are even missleading. Often they don't cover all the call options. Complicated function calls should be made with keywords anyway. Leave positional only parameters to obvious functions such as pow() or sqrt(). The speed hit should be minimal. You are using Python, where dot access is a much more bigger performance eater than keyword arg functions.
- teddyh 5y agoI agree with everything in the article, but I would like to add one observation: The article uses as an example of two arguments, a byte string and a string specifying the character encoding of the first argument. Having two arguments so strongly associated with each other as separate arguments is a slight code smell. One should contemplate unifying them into a compound type (like a class instance) which includes both arguments. It’s not always reasonable, of course, and may add more complexity than it saves. But one should keep an eye out for this.
- blip54321 5y agoThat tends to turn Python into Java....
- teddyh 5y agoYes, you should not do it in case it doesn’t help. But it sometimes does help.
- smitty1e 5y agoA class seems heavy. The tuple() is a great way to keep it light.
- teddyh 5y agoUse a named tuple. This way, you can turn it into a class if it ever becomes necessary without changing any other code.
- SethMLarson 5y agoI'd recommend dataclasses over namedtuples. In almost every case the "iterability" of a namedtuple ends up not being necessary (and can be a footgun!) what you really want is a lightweight namespace with types i.e. dataclasses!
- teddyh 5y ago
- raffraffraff 5y agoI would love to live in a world where articles like this included flashcards that you could instantly add to your Python Anki deck. Instead of what I do: leave the tab open forever or bookmark it (and never see it again).
- throwamon 5y agoAs someone who suffers from the same problem, something like SuperMemo may be a close enough solution. I've never used it myself, but I know it has features such as "incremental reading" where you add pages to the database and mark pieces of it to read a little at a time.
- pugio 5y agoCheck out https://withorbit.com https://withorbit.com - an ongoing research project (and set of tools on github) to embed SRS into any essay/post. If more people adopted it, you might have what you want.
- BerislavLopac 5y agoThat sounds like a job for a browser extension... A quick search comes up with Anki Quick Adder [0] for Chrome, but nothing equivalent for Firefox. [0] https://chrome.google.com/webstore/detail/anki-quick-adder/gpbcbbajoagdgnokieocaplbhkiidmmb https://chrome.google.com/webstore/detail/anki-quick-adder/g...
- livinglist 5y agoI’m more in favor of Dart’s approach: void foo(int? num, {String? text}, [List<int> nums]){}
- physicsguy 5y agoWeirdly I literally saw this for the first time this week. I’ve been programming in Python for 8 years!
- kuang_eleven 5y agoI can't see the use of this in almost any code. All of the "bad" examples they gave just seemed perfectly fine, and if they make sense to the user of the library, there's no reason to disallow them. There are rare cases that actually call for keyword-only and (even more rarely) positional-only arguments, but unless they are required for your usecase, please do not enforce arbitrary argument types on your users.