24 ms·
What’s New in Python 3.8
- maest 7y agoCan I chain the walrus operator? All examples I've seen were part of if/while blocks. Something like: r1 = foo(x:=bar) r2 = baz(x)
- metalliqaz 7y agoThis is the release that contains the controversial assignment expressions, which sparked the debate that convinced GvR to quit as BDFL. They didn't select my preferred syntax, but I'm still looking forward to using assignment expressions for testing my re.match() objects. I haven't used 3.8.0 yet but I hope its a good one because 2020 is the year that 2.7 dies and there will be a lot of people switching.
- kbd 7y agoI'm stoked about the walrus operator. Ever since I heard it was being added I've grumbled when writing code that would have been clearer with it. Of course I have to ask, what was your preferred syntax?
- mkl 7y agoNot OP, but maybe it's "as": if re.match(pattern, string) as m: #use m Seems a bit more Pythonic, as "as" is already used like this with "with". Either one would be fine with me and useful.
- metalliqaz 7y agoyep, that's the one!
- TremendousJudge 7y agoIt's already used in imports as well! It was the better choice, I don't know which arguments convinced them otherwise
- kbd 7y agoI think I remember seeing something about the "as" syntax. Wish I could find what I read, IIRC some arguments convinced me that the walrus operator was an improvement.
- metalliqaz 7y agoit is discussed in the PEP https://www.python.org/dev/peps/pep-0572/#alternative-spellings https://www.python.org/dev/peps/pep-0572/#alternative-spelli...
- mixmastamyk 7y agoUnfortunately, none of the reasons listed against are very accurate.
- mixmastamyk 7y agoThe arguments were based around also supporting complex multiple assignments and being to be able to do them anywhere, not just if… and while…, list-comps, etc. Of course neither of those things have been seen in the wild or production code since. Some folks complain even the simple case above is less readable. "as" was the Pythonic choice, rather than the C/Pascalic one.
- diminoten 7y agoBecause of the luddites at RedHat, Python2.7 isn't actually dead until 2024. It's infuriating. https://access.redhat.com/solutions/4455511 https://access.redhat.com/solutions/4455511
- mistrial9 7y agothe emotional content outweighs the objective situation here; also humorous since Luddites are commonly misunderstood per https://en.wikipedia.org/wiki/Luddite https://en.wikipedia.org/wiki/Luddite
- diminoten 7y agoNot misunderstood; luddites (lowercase l, or at least the generalized form) means something different than Luddites (capitalized L).
- jimktrains2 7y agoI'm fairly certain the lowercase l version is the same, but the Luddites are remembered as being ant technology, not pro labour.
- diminoten 7y agoA luddite, generally, is one who is anti-technology. A Luddite, specifically, is a member of a 19th century movement to prevent automation from taking their job. It's insanely pedantic to try and point out the difference, given the ease with which one can find the generic definition.
- lidHanteyk 7y agoIt's almost as if the Python Software Foundation isn't capable of killing the Python 2 language unilaterally without the Python community's consent.
- diminoten 7y ago
- Rebelgecko 7y ago>They didn't select my preferred syntax I don't write much python so there's probably something obvious I'm missing, but I don't see why they didn't use "=". Is there some significant difference between assignment expressions and assignment statements that makes it worth having distinct syntax?
- jimktrains2 7y agoYes, there is. If x = 1 Has been the source of many errors in many languages. Forcing assignment to be more than a 1 character difference from the equality operator prevents this.
- jorams 7y agoI may be missing something, but := is still only a 1 character difference, isn't it?
- chungy 7y ago:= is basically the "yes, I really mean it" version, whereas bare = might just be a simple typo.
- chrisshroba 7y agoIt is, but many intro programmers (and non-intro programmers!) often forget to use == instead of = for comparison, because in the real world, = more often implies equality, rather than assignment. So a novice might mistakenly type `if x=1:` but they would be unlikely to accidentally type `if x:=1:`.
- madhadron 7y agoMakes you wonder why we switched from = is equality and := is assignment like it was in the ALGOL family.
- jimktrains2 7y agoI should have said single-character additions or deletions . == And = have a levenstein distance of 1, == and := is 2. You can't simply make a typo and change an equality check to assignment. So, wiki defines levenstein distance as including substitution, but I was taught or at least remember it only being additions and deletions?
- DonaldPShimoda 7y ago> I'm still looking forward to using assignment expressions for testing my re.match() objects. The fact that this is the go-to example that everybody is using in justifying the introduction of the assignment expression convinces me that the real problem lies with the re module's API. (To be clear: I will also be using assignment expressions for this case, but I don't think assignment expressions are really in line with the overall design of Python.)
- fjp 7y agore's API sucks but I'm looking forward to safe dictionary access with assignment as well. No more if my_map.get(key) is not None: // do something with my_map[key]
- DonaldPShimoda 7y agoHere the "better" solution (imo) would be support for pattern matching: match my_map.get(key): case None: // do thing (or nothing, i.e., pass) case Some(val): // do other thing Scala seems to have figured out how to get pattern matching over arbitrary data (i.e., not statically-defined algebraic datatypes). I'd like to see this come to Python. (Normally I'd fight for pattern matching to always provide static type safety guarantees, but in Python it seems completely reasonable to omit such checks.) EDIT: But you're absolutely right that this is a place where assignment expressions will be used regularly, so thank you for pointing that out!
- supakeen 7y agoArguably one of the hotter debated functions is assignment-as-expression through the := or walrus operator. Quite happy with the new SyntaxWarning for identity comparison on literals and missing commas :) Especially neat is also the `python -m asyncio` shell which allows you to run top-level awaits in your repl instead of needing to start a new event loop each time!
- j88439h84 7y agoIPython has supported top-level async for a while too, plus many other features!
- airstrike 7y agoThe expansion of f-strings is a welcome addition. The more I use them, the happier I am that they exist https://docs.python.org/3/whatsnew/3.8.html#f-strings-support-for-self-documenting-expressions-and-debugging https://docs.python.org/3/whatsnew/3.8.html#f-strings-suppor...
- heavenlyblue 7y agoOne thing I vastly dislike with them is that they are still expanded in logging, while they are not expanded when logging is using "the old way".
- Will_Do 7y agoWhat do you mean the old way? Will it print what foo is if I type logger.info("{foo=}")?
- zaphirplane 7y agoLogging.info(“%s %s”, name, country”) the string isn’t expanded if the logging is set to warn. While with your example the string is expanded then discarded
- falcor84 7y agoHow would you fix the issue without breaking existing semantics? The way I see it, it's a necessary price to pay, and I just continue to use c-style forming strings in logging.
- eru 7y agoThe clean way would be to introduce laziness. But yeah, can't do that in Python.
- skunkworker 7y agoThis makes clean string interpolation so much easier to do, especially for print statements. It's almost hard to use python < 3.6 now because of them.
- bratao 7y agoI do not know exactly what caused this, but my internal project test-suite got a much appreciated 5% speedup! Thank you Python team!
- Alex3917 7y agoNice! My test suite got around 20% faster when going from 3.6 to 3.7. That’s almost like buying a whole new computer.
- The_rationalist 7y agoI you care about performance, maybe you should try pypy (the alternative python compiler)
- bratao 7y agoI try PyPy every 3 months. It has improved greatly and for some periods I migrated to it. But for this particular project, most of time is spent inside lxml, pandas, scikit-learn and other extensions. CPython is actually faster than PyPy for this project. Maybe GraalVM / GraalPython can improve on this use-case.
- vojta_letal 7y agoLike, if graalpython gets ever released.
- santiagobasulto 7y agoShared Memory is the star of this release IMHO.
- diminoten 7y agoIs shared memory one of those things that I should try to access/use immediately, or wait for someone to write a wrapper library around, due to the large number of edge cases/strangeness that might occur?
- sidlls 7y agoWhy not both? You get a great feel for what the edge cases are and how they occur, and thus a better understanding of why decisions in "wrapper libraries" were made, when these edge cases bite you.
- diminoten 7y agoMostly because I don't want to be up at 3am on a Saturday night debugging production code...
- deleted 7y ago[deleted]
- svara 7y ago> Added new multiprocessing.shared_memory module Hard to understand why this is so far down. This is fantastic news!
- deleted 7y ago[deleted]
- ohazi 7y ago> The typing module incorporates several new features: > A dictionary type with per-key types. Ah, I've been waiting for this. I've been able to use Python's optional types pretty much everywhere except for dictionaries that are used as pseudo-objects, which is a fairly common pattern in Python. This should patch that hole nicely.
- j88439h84 7y agoIMO A better fix is to use http://attrs.org http://attrs.org or dataclasses to replace the dicts entirely.
- deleted 7y ago[deleted]
- emddudley 7y agoAgreed--if you're going to go through the trouble of adding detailed type hints to describe a dict, you're like 90% of the way to a dataclass with better usability.
- ben509 7y agoAnd then use a library like json-syntax[1] to translate those into JSON. [1]: https://pypi.org/project/json-syntax/ https://pypi.org/project/json-syntax/
- ledauphin 7y agothis looks interesting. we use cattrs, which has worked well for us but has a long-delayed 1.0 release.
- hermitdev 7y agoOne of the features I'm looking forward to using is the kwdargs support in dataclasses. Honestly, find it so much more useful and intuitive than the 3.7 positional only.
- ledauphin 7y ago
- CivBase 7y agoAs a developer who has primarily developed applications in Python for his entire professional career, I can't say I'm especially excited about any of the "headlining" features of 3.8. The "walrus operator" will occasionally be useful, but I doubt I will find many effective uses for it. Same with the forced positional/keyword arguments and the "self-documenting" f-string expressions. Even when they have a use, it's usually just to save one line of code or a few extra characters. The labeled breaks and continues proposed in PEP-3136 [0] also wouldn't be used very frequently, but they would at least eliminate multiple lines of code and reduce complexity. PEP-3136 was rejected because "code so complicated to require this feature is very rare". I can understand a stance like that. Over complicating a language with rarely-used features can definitely create problems. I just don't see why the three "headline" features I mentioned are any different. [0]: https://www.python.org/dev/peps/pep-3136/ https://www.python.org/dev/peps/pep-3136/
- ageofwant 7y agoI take this as a positive sign of Python's maturity.
- smitty1e 7y ago. . .and the threat of Just Another Vict'ry Announcement (JAVA) as the need to add "sizzle" to the next version looms.
- chooseaname 7y agoRock and a hard place, no? Either you keep adding to a language and people keep using it, or you stop adding to a language and people call it a dead language and stop using it. Most devs don't understand that software can be done and still be useful.
- eru 7y agoWell, you could also try to remove from the language. Like how they removed the `print` keyword when going from Python 2 to Python 3. But removing is harder than adding.
- amanzi 7y agoReal Python have a great post out today going through most of the changes: https://realpython.com/python38-new-features/ https://realpython.com/python38-new-features/ They have a lot of code samples and examples about how and when to use the new features.Personally, I love the new debugging support in F strings.
- rapfaria 7y agoToo bad I'm losing good articles like this one because of those patronizing, click-baity newsletters that they started sending out a year or two ago.
- amanzi 7y agoThey appear to have toned down their marketing efforts recently. You no longer get bombarded with clickbait pop ups or alerts.
- robocat 7y agodef f(a, b, /, c, d, *, e, f): Wow: IMHO that is a very ugly syntax to define a fn with 6 parameters, although it looks to be a path dependency on previous decisions (*, and CPython ,/) and clearly there was much discussion of the need for the functionality and the compromises: https://www.python.org/dev/peps/pep-0570/ https://www.python.org/dev/peps/pep-0570/ It amazes me to see how certain features make it into languages via community/committee (octal numbers in JavaScript - arrgh!). One thing I find really difficult to deal with in languages is the overloading of different syntactic(edit:semantic) usages of different symbols, which itself is a result of limiting ourselves to the ASCII symbols that can be typed. I don't recall written mathematics having the issue badly (although I haven't had to write any for a long time!).
- BurningFrog 7y ago> which itself is a result of limiting ourselves to the ASCII symbols that can be typed I think we're ready for programming languages using some visually good Unicode characters, instead of overloading `[]{}!@#$%^&*()-_/` for everything!
- VVertigo 7y agoI’ve been looking at making up a second keyboard with a bunch of useful characters on it (similar to Tom Scott’s unicode keyboard) and learning Perl 6 to make use of it. I’m thinking that’s going to be my Winter Project/New Year’s resolution this year.
- jfim 7y agoMany languages allow that. Scala allows characters in the math symbols (Sm) and other symbols (So) Unicode categories as identifiers for functions and variables, and APL has a rich notation that relies on many single character operators.
- robocat 7y agoThere are programming fonts that use ligatures to convert >= to ≥, or -> to →, so the source code remains in ASCII but symbol sequences show as unique Unicode characters. A next step could be for common dev environments to actually convert symbol/key sequences to operators (how do APL programmers do it?) Avoiding ambiguity and semantic overloading of ASCII symbols would surely help beginners (if also given a UI that clearly exposes ways to enter the new symbols). I always find one letter operators extremely strange too like u"word" s/foo/bar/ etc. It seems a shame we can type in hundreds of Unicode symbols on a mobile virtual keyboard, but not readily on a physical keyboard. JavaScript has supported Unicode for a long time, but the core language doesn't use it at all.
- herpderperator 7y agoDamn... this is rather confusing: https://www.python.org/dev/peps/pep-0572/ https://www.python.org/dev/peps/pep-0572/ I really like the walrus operator, but I didn't realize how many "you shouldn't do this" and "this is too hard already" cases exist where they are discouraging using the walrus operator.
- pcr910303 7y agoI like the additions of the f-strings and walrus operator, but I find myself wishing a breaking-release removing the old features that the new features covers. Python's philosophy was to have one way to do something, but the current situation of Python is very inconsistent. Python 3 has like 4~5 ways to format strings, and due to the addition of the walrus operator, we have (I understand the differences between := and = but) two different syntaxes for variable declaration/assignment. I understand that Python can't break all kinds of code (as the 2->3 conversion is still a pain), but still I imagine a Python-esque language without all the warts that Python have with it's 'organic' growth.
- jakear 7y agoThat's a good use case for a linter. Ban outdated constructs in your code, but still allow you to depend on things that use them. Beats another 2->3 split again.
- pcr910303 7y agoYeah, and I already use linters to remove all outdated constructs; but... It's a pity that "There's only one way to do it" doesn't work in 2019 :-(
- gimboland 7y agoIt was never "there's only one way to do it". It is: "There should be one-- and preferably only one --obvious way to do it." The core of that statement is "There should be one obvious way to do it" - there's no "only" there, it just says that when you need to do something, there should be an/some obvious way to do it. Then, preferably, that should be the only obvious way — though of course that doesn't preclude there being many other less-obvious ways. With string interpolation we've certainly now got multiple ways to do it; that doesn't violate the principle. I agree that at least two of those are "obvious" (f-strings and .format()), and you could argue that %-interpolation is obvious too — but none of that is in violation of the principle that there should be an obvious way to do it, just of the preference that there's only one. Finally it's worth remembering where this idea came from: it was in contrast to the perl mantra of "there's more than one way to do it", and a reaction to the resultant confusion frequently experienced when reading someone else's perl code — this was python saying "we're not perl, we value clarity and comprehension". I think that much of that problem was bound up in perl's syntax choices, and that in the cases in python where there's more than one way to do it (say, string formatting, dataclasses/attrs/namedtuples/etc.), it's usually pretty obvious what machinery is actually being used. When was the last time you looked at a line of python and said "I have no idea what the fuck is going on here?" That was a frequent experience with perl in the heady days of the late 1990s.
- archie2 7y agoI don't mind the walrus operator, but holy cow the "positional operators" syntax is completely unintelligble...what the hell were they thinking?!
- toyg 7y agoIt really is not supposed to be used unless you are wrapping a C library. Or at least that’s the original reasoning, I think. Let’s hope it doesn’t get abused.
- w-m 7y ago> The list constructor does not overallocate the internal item buffer if the input iterable has a known length (the input implements __len__). This makes the created list 12% smaller on average. (Contributed by Raymond Hettinger and Pablo Galindo in bpo-33234.) Wow. I believe it's a stated goal of CPython to prefer simple maintainable code over maximum performance. But relatively low-hanging fruit like this makes me wonder how much overall CPython perf could be improved by specialising for a few more of these.
- Pxtl 7y agoUgh, I hate assignment expressions. I liked that they were missing from Python. I've been coding in algolesque languages for 20 years and hiding assignments inside of expressions instead of putting them on the left like a statement has always tripped me up.
- jtdev 7y agoBut, but, but... now you don’t need to write that extra line of code! It’s going to make everything sooooo much better, code will practically write itself now. I’ll just leave this here: “There should be one—and preferably only one—obvious way to do it.”
- codr7 7y agoAt this point it's about as true as G not being evil. Which is fine by me, it was a silly idea to begin with. What you really want is separated concerns that compose well, obvious here doesn't mean anything over there.
- ewidar 7y agoWell there is now one obvious way to do most things that are targeted by this change, using the walrus operator.
- heyflyguy 7y agoman do I wish they would make multiprocessing easier
- mintplant 7y agoSubinterpreters are coming in 3.9, which should fill most of the same roles as multiprocessing but without the complexities and edge cases of multiple real OS processes. https://www.python.org/dev/peps/pep-0554/ https://www.python.org/dev/peps/pep-0554/
- blumomo 7y agoAccording to https://www.python.org/dev/peps/pep-0554/#provisional-status https://www.python.org/dev/peps/pep-0554/#provisional-status they should already be present in 3.8 for evaluation.
- agf 7y agoI gave a talk on this at the PyBay conference this summer, and more recently at the ChiPy meetup in Chicago last week. Presentation: https://docs.google.com/presentation/d/1a3Zoav7NmeN_gXjGcV_lalROR8Mo8CxDpgV1qAdof9U/edit?usp=sharing https://docs.google.com/presentation/d/1a3Zoav7NmeN_gXjGcV_l... Video from PyBay: https://www.youtube.com/watch?v=OtdQN24Z5MA https://www.youtube.com/watch?v=OtdQN24Z5MA It covers assignment expressions in some depth, as well as highlights elsewhere.
- mintplant 7y agoBuried in the notes for the `typing` module: > “Final” variables, functions, methods and classes. See PEP 591, typing.Final and typing.final(). The final qualifier instructs a static type checker to restrict subclassing, overriding, or reassignment: > pi: Final[float] = 3.1415926536 As I understand it, this means Python now has a way of marking variables as constant (though it doesn't propagate into the underlying values as in the case of C++'s `const`). The equivalent Java: final float pi = 3.1415926536;
- xapata 7y agoI don't see the point of `final` without an optimizing compiler. Name mangling is sufficient for stashing references to avoid accidental side-effects of overriding.
- eru 7y agoYou can guard yourself against overriding in the same module this way, too. For name mangling, I think you need to start your variable with underscores, and then it won't be accessible for reading outside the module either?
- Sean1708 7y agoFor modules you can access the variable just fine, but for classes you need to use the mangled name: $ cat >foo.py __FOO = 1 class Foo: __FOO = 2 $ cat >bar.py import foo print(foo.__FOO) print(foo.Foo()._Foo__FOO) $ python3 bar.py 1 2
- xapata 7y agoNope, you don't need to start the name with underscores. class Foo: bar = 'public' __bar = bar # stashed
- spott 7y agoThe thing is, it is only enforced in mypy... code that modifies a Final object (pi = 3 for example) later on will run fine.
- ram_rar 7y agoDoes the python community care about concurrency at all? I havent seen anything new in terms of concurrency in a while. I might be wrong about this, but walrus operator seems like a gateway to writing obfuscated perlesque code.
- quietbritishjim 7y agoThere were some changes to asyncio in this release but they were pulled at the last moment so they can better sign with Turio.
- aeyes 7y ago3.8 brings shared memory to multiprocessing: https://docs.python.org/3/library/multiprocessing.shared_memory.html#module-multiprocessing.shared_memory https://docs.python.org/3/library/multiprocessing.shared_mem...
- sys_64738 7y agoLooks like python is trying to out C++ the C++ language with kitchen sink bolt ons.
- qwerty456127 7y agoStill no pattern matching and no immutable vars :-(
- svnpenn 7y ago> In this example, the assignment expression helps avoid calling len() twice: if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)") Um, no it doesnt?: a1 = [10, 20, 30] n1 = len(a1) if n1 > 2: print(f'{n1} is greater than two')
- adjkant 7y agoI'm not a huge fan of the := operator for Python for clarity and single one clear way reasons, but the draw is the saved line of code here that is the "help"
- hermitdev 7y agoYes, but your example is less efficient than the new code. Remember: every variable is an assignment into a dict, and every lookup a query into a dict. Reducing name lookups and assignments can yield good speedup in tight loops. For instance, caching os.path.join, os.path.split into local names can significantly speed up tight loops iterating over a filesystem. For example, os.path.split is potentially 5 dictionary lookups. Checking locals, nonlocals and globals for os. Then another to find path, and a final one for split. And this happens at runtime, for every invocation.
- murkt 7y agoLocal variables aren’t stored in a dict, likewise when a class has defined __slots__. Globals, modules and usual classes do use dicts internally, but locals do not. So from the efficiency standpoint it’s (almost?) the same. I haven’t checked the bytecode, maybe there is some slight difference.
- hermitdev 7y agoIt has been a while since I've looked at the implementation details. How does locals() work, then? It does return a dict. Slots are definitely an edge case I did not address. I honestly dont know how name lookup works in any version of Python. Edit: I realize that local name lookup doesn't need to follow the result of the locals() built-in function.
- deleted 7y ago[deleted]
- Timothycquinn 7y agoAssignment expression is something I miss from JavaScript which I used a lot to strip lines of code. Great to see in Python.
- jxy 7y agoIt's interesting to see Python's gradual acceptance to TMTOWTDI.
- vikinghckr 7y agoDisappointing that Python sill has no support for a sorted container in its standard library, akin to C++ `set` or `map` classes.
- craftyguy 7y agoBut it does have a method to sort containers in its standard library, `sorted`, that C++ doesn't have. And it's trivial to use it to sort lists, sets, and dicts...
- vikinghckr 7y agoC++ also has the `sort()` function that allows you to sort any unsorted container. But that's not a replacement for a sorted container like `set` or `map` though. Because `set` or `map` allows you to insert elements at O(log n) runtime. If you have to sort every time you insert using the `sort()` or `sorted()` functions, the run time becomes O(n log n).
- carapace 7y agohttps://docs.python.org/3.0/library/bisect.html https://docs.python.org/3.0/library/bisect.html > This module provides support for maintaining a list in sorted order without having to sort the list after each insertion.
- vikinghckr 7y agoProblem with bisect is that bisect.insort() insertion is O(n), whereas C++ set.insert() is O(log n).
- stfwn 7y agoIt is somewhat strange that Python does not have a binary tree in the standard library. I also couldn't find any discussion on the topic either. It might be a nice contribution. Edit: it was coined a few times on the python-ideas mailing list but it seems it just died a silent death there. https://mail.python.org/archives/list/python-ideas@python.org/message/3XA5XVGOPQNOVP6PRODTARAFPFXWG3PX/ https://mail.python.org/archives/list/python-ideas@python.or...
- bp294 7y agoInteresting! Thanks for the share!
- ameliaquining 7y agoAnyone else most excited about PYTHONCACHEPREFIX? :-P
- blumomo 7y agoThe new assignment expression is great and I wish that an optional operator (`?`) and Elvis operator (`?:`) will make it to Python one day, too. I would love to write: v = obj?.prop1?.prop2 ?: "default" instead of long if conditions: v = obj.prop1.prop2 if obj and obj.prop1 and obj.prop1.prop2 else "default" A PEP for Python 3.8 existed but has been deferred: https://www.python.org/dev/peps/pep-0505/ https://www.python.org/dev/peps/pep-0505/
- cryptos 7y agoIt would be nice if the Python web site would be mobile friendly.
- molteanu 7y agoIs Python now becoming the new C++?
- davb 7y agoThis is fair criticism. I've worked with Python for many years now, and one of the things that attracted me was that there was always a fsirly static "Pythonic" way to do things. The language has now grown so much that 80% of the people only use 20% of the language, but not always the same 20%, making it difficult to read other people's code. And all the syntactic changes contribute to fragmentation (not every project can have its Python interpreter upgraded regularly). There's something to be said for a more stable, if less elegant, language.
- probably_wrong 7y agoI would argue that it's becoming the new Perl. I mean, look at this: f"Diameter {(diam := 2 * r)} gives circumference {math.pi * diam:.2f}" If this is not write-only code, I don't know what is.
- tolgahanuzun 7y agoUpdates on `f-string` are quite fun. :) `f'{username= }'` 'username="tolgahanuzun"' I like it.
- spicyramen 7y agoI'm still migrating from 2.7...to 3.5
- louis8799 7y agoNew "f-strings support = for self-documenting expressions" but you cannot use f-strings as doc string ;)
- Xophmeister 7y agoThis got missed from the release announcement, but now there's `functools.singledispatchmethod`,[1] as the class method sibling to `functools.singledispatch`.[2] This allows you to overload the implementation of a function (and now a method) based on the type of its first argument. This saves you writing code like: def foo(bar): if isinstance(bar, Quux): # Treat bar as a Quux elif isinstance(bar, Xyzzy): # Treat bar as an Xyzzy # etc. I understand runtime type checking like that is considered a bit of a Python antipattern. With `singledispatch`, you can do this instead: @singledispatch def foo(bar:Quux): # Quux implementation @foo.register def _(bar:Xyzzy): # Xyzzy implementation With `singledispatchmethod`, you can now also do this to class methods, where the type of the first non-self/class is used by the interpreter to check the type, based on its annotation (or using the argument to its `register` method). You could mimic this behaviour using `singledispatch` in your constructor, but this syntax is much nicer. [1] https://docs.python.org/3/library/functools.html#functools.singledispatchmethod https://docs.python.org/3/library/functools.html#functools.s... [2] https://docs.python.org/3/library/functools.html#functools.singledispatch https://docs.python.org/3/library/functools.html#functools.s...
- bouncing 7y agoI can definitely imagine some places where this replaces type-checking, but it still seems like a bit of an unfortunate anti-pattern to me, since it's really a sort of C/C++ style function prototype match. My immediate thought is that it's going to be hard for PyCharm to reliably point me to a function definition.
- heavenlyblue 7y ago>> My immediate thought is that it's going to be hard for PyCharm to reliably point me to a function definition. I am certain PyCharm is going to special-case these decorators in their next release.
- gimboland 7y agoNice. I missed this feature only a few weeks ago. Good to know it's landed!
- omginternets 7y agoI stepped away from Python for about a year, and now I'm coming back to it. I hardly recognize the language. I'm not happy about this at all. I don't really have a point, except that Python 3 feels like a moving target.
- probably_wrong 7y agoI feel the same way as you do. For me, which version of an interpreter I'm using should be the kind of issue I only need to worry when solving extremely specific, deep-level problems. Python 3+ breaks this pact too often for my taste. Considering this f-string example taken from another announcement: f"Diameter {(diam := 2 * r)} gives circumference {math.pi * diam:.2f}" This is valid Python 3.8, but it's not valid in Python 3.7 (no walrus operator). And removing the walrus operator still doesn't work in Python 3.5 (no f-strings). On top of that, other comments already mention how f-strings have lots of weird corner cases anyway. The entire point of Python in my circle of friends was that it made programming easy. Instead, I feel more and more in need of those "It works in my machine!" stickers. And good luck solving these issues if you are not a full-time programmer...
- Liquid_Fire 7y agoI'm not sure why you frame this as an issue with Python 3. This has always been the case, even in the 2.x days every release added new features, and if you ran code using them in an older version it wouldn't work. The minor releases are always backward-compatible, so just run the latest version and everything will work.
- omginternets 7y agoThe issue is that the ecosystem as a whole tends to follow the tip of the version chain. This means that any human-oriented Python stuff (e.g. documentation/tutorials/code-review/etc...) requires you stay up to date with the language changes. Asyncio was the worst culprit, as it essentially introduces an inner-platform with its own dataflow semantics, but at least there the upsides were large and tangible.
- CommieDetector 7y agoStill using space for indentation?
- cutler 7y agoAny idea how long it will take before it's an option with pyenv?
- varelaz 7y agoEverything of this looks like syntax sugar. I would expect more work on internals. Python has a lot of awkward edge cases in standard lib. In a lot of cases None is valid output for not-done states. Also I hate multithreading programming in Python 3, it has all drawbacks of C with additions of GIL.
- nilsandrey 7y agoThe := operator is the assignment operator on Object Pascal, just saying, remembering my old days. BTW not so old for everyone -> https://news.ycombinator.com/item?id=15490345 https://news.ycombinator.com/item?id=15490345
- robomartin 7y agoI don't understand why the walrus operator is needed at all. Why not allow, this to work: if m=whatever(): do_something Why create a new assignment operator? For all the talk about making code not confusing, etc., some of these decisions sure seem nonsensical. Oh, OK, it confuses passing arguments into a function by name? Really? C'mon. Also, I can't understand the nearly religious rejection of pre and post increment/decrement (++/--) and, for the love of Picard, the switch() statement. I enjoy using Python but some of these things are just silly. Just my opinion, of course. What do I know anyhow? I've only been writing software for over thirty years while using over a dozen languages ranging from machine language (as in op codes) to APL and every new fad and modern language in between. As I watch languages evolve what I see is various levels of ridiculous reinvention of the wheel for very little in the way of real gains in productivity, code quality, bug eradication, expressiveness, etc. Python, Objective-C, Javascript, PHP, C# and a bunch of other mutants are just C and C++ that behave differently. Sure, OK, not strictly true at a technical level, but I'll be damned if it all doesn't end-up with machine code that does pretty much the same darn thing. The world did exist before all of these "advanced" languages were around and we wrote excellent software (and crappy software too, just like today). What's worse is that some of these languages waste a tremendous amount of resources and clock cycles to do the same thing we used to do in "lower" languages without any issues whatsoever. Mission critical, failure tolerant, complex software existed way before someone decided that the switch() statement was an abomination and that pre and post increment/decrement are somehow confusing or unrefined. Kind of makes you wonder what mental image they have of a programmer, doesn't it? Really. In my 30+ years in the industry I have yet to meet someone who is laid to waste, curled-up into a fetal position confused about pre and post increment/decrement, switch statements and other things deemed too complex and inelegant in some of these languages and pedantic circles. Geez! </rant off>