39 ms·
Things to use in Python 3
- j88439h84 7y agoThe "Implicit namespace packages" item is not correct. Those are for a a specific packaging scenario which doesn't come up in normal usage. Packages should have an __init__.py file in general.
- giancarlostoro 7y agoIf the file is going to be empty I fail to justify the effort. It is implicitly a package. Is there a case where an empty init file makes sense in Python 3?
- jsmeaton 7y agoThanks, this was the only item I wasn't sure about, and reading PEP 420 didn't really make it clear how this would benefit regular applications.
- baseballMan 7y agoI'm by no means a hardcore python dev but I feel like these are all pretty basic, common things. No?
- nerdbaggy 7y agoI don’t think an LRU cache is basic
- jakear 7y agoIf you’ve ever needed it, and I imagine most people have, it shows up on any web search. That being said I usually end up rolling my own that can serialize complex objects.
- dagw 7y agoIf you’ve ever needed it, and I imagine most people have, it shows up on any web search. It didn't last time I googled it (because it didn't exist then), so I had no idea it existed.
- whoevercares 7y agoWe probably should compare the timeline when those features are added to other languages
- jedberg 7y agoThey're basic but also things you'd never look up, especially if you've been doing python a long time. For example, I just learned about f strings, because why would I need to ever look up if there is a replacement for .format()? And the LRU cache. I've been hand rolling that for years, but I never thought to see if they had added it to the standard library, because why would I look?
- mixmastamyk 7y agoIt pays to look thru the stdlib every so often, there is just so much there, and plenty of dark corners (in the Warcraft sense) to look in. I hand rolled stuff in itertools/functools for years before discovering them.... collections Counter, etc. Or how about str.partition instead of try: str.split() ?
- Twirrim 7y agoOn a related note, every couple of years I make an effort to man page every cli tool I use, and re-read the man page, just in case. Most times I discover there is some argument that I've missed before in a tool (or has been added in the intervening time)
- jedberg 7y agoWhen my dad sold cars he’d always tell his customers to read the car manual again after six months for the same reason.
- stOneskull 7y agodon't you read about what's new when new versions come out?
- dagw 7y agoI've been programming python, on and off, since 2001, and I still learnt a couple of things.
- iandanforth 7y agoTIL - Enum, auto(), @dataclass, and that classes don't need (object) anymore. Neat!
- DonaldPShimoda 7y agoEDIT: nope, nope, this is all wrong. My mistake. Ignore everything else here. > classes don't need (object) anymore My friend, old-style classes became unnecessary with the release of Python 2.2 — almost 20 years ago now [0]. I'm afraid you've been living in the past. :) [0] https://wiki.python.org/moin/NewClassVsClassicClass https://wiki.python.org/moin/NewClassVsClassicClass
- Myrmornis 7y agoNope, she/he has not. (object) were the new style classes!
- DonaldPShimoda 7y agoOh man, major brain fart there. You're completely right of course. I was thinking of the transition to classes-as-types in general. Probably would've helped if I actually read the page I linked...
- nerdwaller 7y agoExtending `object` was necessary until 2.7 when it became the default and old style classes were removed entirely in 3. So I think while the GP comment recently learned they don’t need to extend `object` anymore, they are/were familiar with new style vs old style classes.
- DonaldPShimoda 7y agoRight! Yes, another commenter pointed that out to me too. I made a goof and misremembered some things haha. Oops.
- auscompgeek 7y ago
- k4ch0w 7y agoF strings have been amazing in my everyday programming. I have been programming in Python for about 8 years now. I'd say some additions to this list are Conda for managing environments and Deep Learning builds such as Cuda on Ubuntu Jupyter notebooks for quick prototyping IPython if you have never seen it before. Requests Library
- nerdbaggy 7y agoBefore I knew about F strings my .formats() were just so long. F strings are nice for sure
- sametmax 7y agoDespite being so cool, it's also a very under utilized feature, as it inherits all the formatting capabilities of format(). With format(), and hence with f-string you can: # Replace datetime.stftime() >>> f"{datetime.now():%m/%d/%y}" '05/15/19' # Show numbers in another base >>> f"{878:b}" '1101101110' >>> f"{878:x}" '36e' >>> f"{878:e}" '8.780000e+02' >>> f"{878:o}" '1556' # Control the display of padding, filling, and precision of numbers >>> 1 / 3 0.3333333333333333 >>> f"{1 / 3:.2f}" '0.33' >>> f"{69:4d}" ' 69' >>> f"{69:=+8d}" '+ 69' >>> f"{69:0=8d}" '00000069' # Center text >>> f"{'foo':^10}" ' foo ' And so many other things, since you can create your custom __format__. Not affiliated, but in this regard, I quite love https://pyformat.info/ https://pyformat.info/ as a format cheat sheet.
- DonaldPShimoda 7y ago> I quite love https://pyformat.info/ https://pyformat.info/ as a format cheat sheet. I never knew this existed but that's awesome! Thanks for the link!
- pbreit 7y agoTo this novice, the "Old" way looks so much better.
- sametmax 7y ago
- Areading314 7y agoI would add to this list: * generators * defaultdict * generators * sets
- mythrwy 7y agoGenerators and sets have been around for a long time I think. They were there in 2.X version like 9-10 years ago when I first used Python anyway and aren't 3 specific.
- jwilk 7y agoGenerators were added in Python 2.2: https://docs.python.org/2/whatsnew/2.2.html#pep-255-simple-generators https://docs.python.org/2/whatsnew/2.2.html#pep-255-simple-g... Built-in set objects were added in Python 2.4: https://docs.python.org/2/whatsnew/2.4.html#pep-218-built-in-set-objects https://docs.python.org/2/whatsnew/2.4.html#pep-218-built-in... defaultdict was added in Python 2.5: https://docs.python.org/2/library/collections.html#collections.defaultdict https://docs.python.org/2/library/collections.html#collectio...
- DonaldPShimoda 7y ago> Type hinting (3.5+) > Static vs dynamic typing is a spicy topic in software engineering and almost everyone has an opinion on it. I will let the reader decide when they should write types, but I think you should at least know that Python 3 supports type hints. I think this gives readers the impression that type hints have anything to do with dynamic vs. static type systems, which isn't true. These are merely annotations that are attached to values. In fact, it's legal to use full strings as type annotations — they have no inherent semantic value. You can gain semantic value by using a tool like MyPy or an IDE like PyCharm, but the type annotations do not in themselves do anything. I think it could be worth clarifying this for readers who are unaware.
- xjlin0 7y agoHow to do Type hinting with argument default values?
- DonaldPShimoda 7y agoPretty straightforwardly: x: int = 0 This makes sense when you see that the variable production in the Python grammar [0] has been updated to essentially read "either a lone variable or a variable with a type annotation". (I highlighted the relevant line of the grammar for you in the link.) [0] https://github.com/python/cpython/blob/master/Grammar/Grammar#L53 https://github.com/python/cpython/blob/master/Grammar/Gramma...
- deleted 7y ago[deleted]
- xtf 7y agoExcept further optimisation in Cython like http://docs.cython.org/en/latest/src/tutorial/pure.html#static-typing http://docs.cython.org/en/latest/src/tutorial/pure.html#stat...
- DonaldPShimoda 7y agoI think this falls under the realm of "gain[ing] semantic value by using a tool like MyPy". The implementation of static typing by way of processing type annotations is an implementation choice, and not a part of the Python language specification.
- jedberg 7y agoWow, today I learned about f strings. That will make my code so much more readable! And no more annoying bugs because I skipped one of the seven references in the string!
- deleted 7y ago[deleted]
- mixmastamyk 7y agoIt reads like sarcasm, but then you drop a real benefit. ((Confusion by New Order playing in the background))
- jedberg 7y agoNo it’s true enthusiasm. The internet has just ruined ! For everyone. :)
- mixmastamyk 7y agoGlad to hear you like it. As a fun fact (and self-back patting), it was I who braved the gauntlet at the python-ideas mailing list to get the idea accepted. Eric Smith did everything else so deserves the credit. Background: turns out that the string prefix was the only ASCII syntax left in Python3, that's why it was chosen. The name "eff string" makes me cringe, but once it stuck there was no stopping it.
- DonaldPShimoda 7y ago> it was I who braved the gauntlet at the python-ideas mailing list to get the idea accepted That explains why you're all over this post ;) Fantastic feature, though. Really. Thanks! Out of curiosity, what name would you have preferred over "f-strings"? "Format strings"? "Interpolation strings"? "I-will-evaluate-expressions-in-curly-braces strings"?
- mixmastamyk 7y ago
- schemathings 7y agoI didn't start using python til 3, but list comprehensions and f-strings are great. I've really been enjoying the coding style.
- speedplane 7y agoThere's no reason why Python 2 can't have the vast majority of these features. It's a shame that the Python continues to ignore the reality of the mess they made with Python 3, and failing to question what was an originally bad idea.
- xxpor 7y agoThis question is done and dusted. There's literally no point in discussing it any more. CPython 2.7 support ends in 7 months. It's time to move on.
- speedplane 7y ago> There's literally no point in discussing it any more. CPython 2.7 support ends in 7 months. It's time to move on. Ah, the classic "nothing to see here, keep moving on" argument. The lack of admission of a bad idea is itself a problem. What happens in a few years when Python 4 renders all Python 3 code incompatible?
- DonaldPShimoda 7y ago> What happens in a few years when Python 4 renders all Python 3 code incompatible? Ah, the classic "they did it once so they'll definitely do it every single time from now on" argument. Nick Coghlan, one of the Python core developers, said "Python 4.0 will merely be "the release that comes after Python 3.9"" [0], so I think your concerns are ill-based. [0] https://www.curiousefficiency.org/posts/2014/08/python-4000.html https://www.curiousefficiency.org/posts/2014/08/python-4000....
- mixmastamyk 7y agoNot to mention some of us are glad lots of things got fixed and not sore in the slightest.
- DonaldPShimoda 7y ago
- croh 7y ago1. f-string and extended-iterable-unpacking reminds ruby. i was really missing them. 2. pathlib is cool. will come pretty handy. 3. Data classes sounds good but there should be only one way to do things, even you end up writing few more lines. 4. type-hints are ok for very very big projects. 5. No comment on implicit-namespace-packages yet as still trying to understand solid use-case.
- DonaldPShimoda 7y ago> Data classes sounds good but there should be only one way to do things Dataclasses greatly simplify generation of simple classes which are unnecessarily filled with boilerplate. I'd argue that they are the one way to do this, and that choosing to manually implement the same naive `__init__` function for every simple class you write is the "wrong" way. (Here I take "simple class" to mean a class which takes in some values during initialization and stores them without anything terribly interesting going on during that initialization. A simple class can have methods defined on it, though.) > type-hints are ok for very very big projects. D: > No comment on implicit-namespace-packages yet as still trying to understand solid use-case. I think it's just... trying to keep your directories "clean"? I also don't really understand the use of this haha.
- croh 7y ago> Dataclasses greatly simplify generation of simple classes which are unnecessarily filled with boilerplate I would love to solve these boilerplate kinds of problems using plugging like emmets. Magic like this feels good when writing but troubles during debugging and customizing. Additionally naive programmers always use such features in wrong situation if they don't get use-case. I really feel sad after seeing so much bad-django-code in production.
- dfinninger 7y ago> 4. type-hints are ok for very very big projects. Great for smaller ones too! I type annotate every function, even def parse_args() -> argparse.Namespace: pass at the top of simple scripts. With a good IDE (VS Code fits here too), the extra language lookups/insight you get are awesome. Command+mouse_hover gives me a great bit of information about args passed into the function if I annotate the inputs.
- fulafel 7y agoOriginally small dynamic languages like Python and Javascript are constantly growing new language/stdlib features but rarely taking anything away. I wonder how this affects learnability, how long will it take for a programming newbie to be able to jump into an existing project or read other people's code. I guess this could be measured and studied, I wonder if someone has done it. I think Python was probably at a pretty good local sweet spot in the complexity:power ratio around the 2.0 version.
- yen223 7y agoPython is definitely heading down that dark path. I wonder how many pythonistas are fully across all of the new syntax coming, like positional-only args or even the infamous assignment expression.
- DonaldPShimoda 7y agoI don't think it's the case that a language needs all of its syntactic sugar to be intuitive or obvious to the initiate. These are things you will acquire over time as you either search the internet for "how do I do X" or you read other people's code that exemplifies them. Though I'd argue that anybody who adopts the "pythonista" label is likely to be somebody who looks through version release notes for these kinds of things. I certainly do!
- sametmax 7y ago2 new syntaxes a years is not a not. I find it quite balanced for a 25 years old language. It's funny, because I always hear people complaining Python move too slowly to stay modern on one side, and then right after some other people saying it goes too fast. My take on this is that people just like to complain.
- voldacar 7y agoYes! Python is getting less pythonic with each new version.
- baq 7y ago
- rcfox 7y agoSimpleNamespace[0] is pretty handy too. It essentially lets you wrap a dictionary and access its keys as member properties. Also, it's kind of weird that the article would mention type annotations and then not mention mypy[1]. [0] https://docs.python.org/3/library/types.html?highlight=types#types.SimpleNamespace https://docs.python.org/3/library/types.html?highlight=types... [1] http://mypy-lang.org/ http://mypy-lang.org/
- DonaldPShimoda 7y agoWhoa, I've never seen the `types` module before! This will actually be very handy for me for what I've been working on lately. Thanks for pointing it out!
- rcfox 7y agoIt's definitely worthwhile going over the standard library[0] every now and then. I always find something interesting to read up on. I recently learned about cmd[1] (which has been around for a long time) and have been using it to write a text adventure game. [0] https://docs.python.org/3/library/index.html https://docs.python.org/3/library/index.html [1] https://docs.python.org/3/library/cmd.html https://docs.python.org/3/library/cmd.html
- rattray 7y agoCurious to see a small code sample illustrating typical usage of SimpleNamespace if you care to share? Docs didn't include one.
- rcfox 7y agoHere's one case I've used it for: foo = json.dumps({'a': 1, 'b': {'c': 2}}) # Pretend you've downloaded some JSON... bar = json.loads(foo, object_hook=lambda x: types.SimpleNamespace(**x)) print(bar.a) print(bar.b.c) print(bar.b.d) # Error bar.b.d = 3 print(bar.b.d) # Works now I mean, you could pretty much do the same sort of thing with namedtuple, except this is mutable and doesn't require a pre-declaration of the keys. It's easier to write off the cuff.
- Grue3 7y ago>f-strings What happened to "explicit is better than implicit"? "Only one way to do stuff"? One of the more baffling Python features if you ask me.
- sametmax 7y agoThis debate already took place. Go back to the python-idea mailing list posts about f-string for a complete back and forth on your point.
- kragen 7y agoIt took place three times actually; Ping proposed string interpolation in 2000 in PEP 215 https://www.python.org/dev/peps/pep-0215/ https://www.python.org/dev/peps/pep-0215/ and it was rejected, or rather simplified by Barry Warsaw in 2002 in PEP 292, which was actually implemented: https://www.python.org/dev/peps/pep-0292/ https://www.python.org/dev/peps/pep-0292/ and remains in modern Python. Barry's optimism that this would satisfy the demand for template strings was of course foolish, but it met with Guido's misguided approval at the time. Fifteen years later, it was proposed a third time as PEP 498 and finally got in in a sane form: https://www.python.org/dev/peps/pep-0498/ https://www.python.org/dev/peps/pep-0498/
- paganel 7y agoExactly, the f-string syntax looks so close to PHP’s way of handling strings that I’m really amazed that it managed to pass and be implemented. I mean, I don’t see that much of a difference between > name = ‘Jane’ > print(f”Hello, {name}”) and PHP’s: > $name = “Jane”; > echo “Hello, $name”;
- ChrisSD 7y agoWhy is looking similar to the PHP method inherently a bad thing?
- paganel 7y agoAbout 15 years ago when I was starting my life as a professional programmer PHP's way of handling strings was seen as inferior to stuff like: > name = 'Jane' > print 'Hello, %s' % (name) but I can't exactly reproduce all the discussions from back then. As for me personally I can see that I dislike the new > print(f'Hello {name}') format because my editor cannot instantly show me that {name} is in a fact a variable, and now that I wrote this down I remember that this was one of the complaints made against PHP's use of "Hello, $name" . But maybe newer editors do in fact recognize {name} as a Python variable, in any case it looks and feels "impure", for a lack of a better word.
- sametmax 7y agoI'm training people in Python regularly and my classroom experience is: ALWAYS USE __INIT__.PY EVERYWHERE. Don't use this namespace feature. You think you understand how it works, but you don't. It will bite you.
- simonh 7y agoI just read the docs on this, but don't really grok the pros-and-cons. Can you give an example of a gotcha? That would be very helpful.
- sametmax 7y agoNamespaces are useful for library providers and os packagers to split sub features of one package and distribute the chunks separately. It will virtually merge dirs with the same name under some circonstances, and won't be importable in some others. You also lose the benefit of having an init file in which you explicitly setup the object you expose for import.
- scrollaway 7y agoAmen. Much as I wish python importing was as powerful as js, that ship has sailed and we're nowhere close to getting rid of the dunder-init file. Also pathlib is .. urgh. This is one of those that shouldn't be in the stdlib. I don't get why it is, but requests isn't.
- IanCal 7y agoBeware lru_cache and mutable objects. I'm on a phone so this will probably contain an error but: @lru_cache def slow(): return {"result": "immutable?} answer = slow() answer["result"] = "no" print(slow())
- IanCal 7y agoCan't edit now, but here's a runnable gist https://gist.github.com/IanCal/d703106344e876728d2aaef67800dfb8 https://gist.github.com/IanCal/d703106344e876728d2aaef67800d...
- andreareina 7y agoIt also won't let you cache on mutable values, so you can't pass in lists or dicts. I've used it on occasion, a lot of the time I ended up rolling my own instead. Usually without expiration since I didn't need it.
- reacharavindh 7y agoI was curious to see how asyncio has matured into such a list.. but it was missing the list. Is it common enough for people to use in scripts to speed up concurrent work yet?
- dagw 7y agoAnecdotally, no. From where I sit, the multiprocessing and threading modules still seem to be the main way to to concurrency in python.
- nurettin 7y agoFrom where I sit (I've been soloing python projects for a few months now) For IO-blocking tasks, asyncio is the way to go and threading is very rarely needed if any. It is very simple to place a bunch of tasks into a list and do asyncio.gather on them, or add timeouts to async methods. For CPU intensive tasks, asyncio actually provides it's own syntax for process pools which are easily interchangeable with thread pools (just change an import alias)
- ozychhi 7y agoWe actually tried switching to asyncio in production, but got worse cpu utilisation and worse latency (vs greenlet). After some benchmarking and tuning, we got a bit better latency, but CPU utilisation was still worse, so we actually ended up swithcing back to just using greenlet :(
- nurettin 7y agoI would not recommend using asyncio for cpu-intensive tasks. Processing pools are much better for that.
- gbajson 7y agoThe example of f-string in the article is quite unfortunate, it suggests using it for logging messages. F-strings shouldn't be used in loggers, because they aren't lazy evaluated.
- bonoboTP 7y agoWhat instead?
- gbajson 7y agoStandard logging functions, without f-strings. So instead of: logging.debug(f'Problem with {x}') use: logging.debug('Problem with %s', x).
- masklinn 7y agoTBF for the vast majority of logging it doesn't really matter. Not to mention the laziness is only the (usually cheap) formatting itself. If you're logging the result of non-trivial expressions (which would otherwise not be computed at all) you have to handroll it. f-strings are mostly unusable for translatable contexts. And format-strings also don't work then (they're a security issue).
- gbajson 7y agoI already experienced performance issue, just because log messages (millions/s) were evaluated, for logger in debug mode, so it really depends on the system.
- tasubotadas 7y agoA cookie for this man!
- deleted 7y ago[deleted]
- purplezooey 7y agoI know types are spicy. But F them. I hate this. If I wanted all this junk I'd stick to C++.
- nurettin 7y agoAre you saying that you exited the C++ scene because dealing with types is tedious? For me, C++ career opportunities were extremely rare to come by and I never had the luxury to change jobs because I didn't like the language in some way. Some people have it too easy.
- dang 7y agoCould you please stop posting unsubstantive comments to Hacker News?
- yrro 7y agoimportlib.resources is an excellent replacement for pkg_resources. with importlib.resources.open_binary('my.package', 'foo.png') as f: ... Avoids the overhead of importing pkg_resources, and hassle of having to call cleanup_resources before the interpreter shuts down. Backports are available for Python <= 3.6 too!
- charliebrownau 7y agoIsnt Python just as bad as Java runtime ?
- alexgmcm 7y agoI just want to thank the author for not using Medium. Far too many tech blog posts use that platform now and I don't like it very at all as it feels really bloated and I can never be sure if what I'm about to click is a 'premium' Medium post or not.
- rhizome31 7y agoGlad to see I'm not the only one thinking like this. Medium is the MySpace of the late 2010s. Good blog post by the way.
- skocznymroczny 7y agoI like that the article doesn't have generic meme images separating each paragraph.
- yzssi 7y agoA few years ago complaining about that would get you flagged. Now it gets upvoted.
- chrshawkes 7y agoI talked about not using it years ago on my YouTube channel and got a rash of shit. I've shown how to replicate that site in minutes as well.
- dna_polymerase 7y agoWow, Medium built such a dysfunctional webservice that people start actively thanking others not to use it - in completely unrelated posts. Nice job.
- maratumba 7y agoBeen enjoying the Make Medium Readable Again (https://chrome.google.com/webstore/detail/make-medium-readable-agai/kljjfejkagofbgklifblndjelgabcmig https://chrome.google.com/webstore/detail/make-medium-readab...) plugin. Removes all the clutter from the page, you won't even know you are on Medium!
- vedyou 7y agoThanks for all these.
- techno_modus 7y agoHere is another short guide on many useful features of Python 3: https://github.com/arogozhnikov/python3_with_pleasure https://github.com/arogozhnikov/python3_with_pleasure
- Already__Taken 7y agoI really hate that __init__.py thing about modules it confuses the F out of teachers and students. Using files without a "program" on the command line is a massive leap as it is.
- auscompgeek 7y agoIn case anyone is stuck on older versions of Python for any reason, here are some backports of some of the listed features: * f-strings: https://github.com/asottile/future-fstrings https://github.com/asottile/future-fstrings (this is a pretty crazy hack, all the way to Python 2) * pathlib: https://pypi.org/project/pathlib2/ https://pypi.org/project/pathlib2/ * typing: https://pypi.org/project/typing/ https://pypi.org/project/typing/ * enum: https://pypi.org/project/enum34/ https://pypi.org/project/enum34/ (doesn't include any additions in 3.5+) * functools.lru_cache: https://github.com/jaraco/backports.functools_lru_cache https://github.com/jaraco/backports.functools_lru_cache * dataclasses: https://github.com/ericvsmith/dataclasses https://github.com/ericvsmith/dataclasses (3.6 only, requires ordered class __annotations__) I'm half-expecting someone to come along with a hacked-up Python 2 backport for implicit namespace packages :)
- isaacremuant 7y agoWith that in mind, the end for Python 2 is less than 8 months away. Something fun to help people feel the "impending doom" and port their projects: https://pythonclock.org/ https://pythonclock.org/
- kragen 7y agoPython 2 is free software. Nobody and no proper subset of people can unilaterally end it. It ends when people stop using it, writing patches for it, and sharing those patches. There might be a lacuna of coordination when the current maintainers step down in 8 months, but the leftover stubborn Python 2 users will come up with some way to share their patches for, probably, decades.
- anentropic 7y agoI was using enum34... then one day I wanted to use a Flag and found it wasn't in there the same author has another library: https://pypi.org/project/aenum/ https://pypi.org/project/aenum/ which includes the latest enum stuff from 3.5 (plus some other things)
- dorfsmay 7y agoHow do you define class variable in a data class?
- nerdwaller 7y agoYou can use `typing.ClassVar[<datatype>]`
- ericvsmith 7y agotyping.ClassVar. See https://docs.python.org/3/library/dataclasses.html#class-variables https://docs.python.org/3/library/dataclasses.html#class-var...
- strange_daze 7y agoI would really like to see custom value types in Python. Is this on the roadmap?
- teekert 7y agoI read quite some things about the data class... in short: If I use a lot of pandas.DataFrames, is this something I should learn about?
- chrshawkes 7y agoYou can now use Python Scrapy with the latest versions of Python 3 for web scraping. Here's an example https://youtu.be/qj6H38Xwvu0 https://youtu.be/qj6H38Xwvu0 It even works on Windows.
- brootstrap 7y agoNot sure anyone will see this but this article is partly trash. When your post is titled "things you are not using in python3 but probably should" and the first section is on f-strings... I was tempted to close the tab then , but i followed thru and did find some interesting things. But seriously f-strings? people have been talking about these for years now, it's not new is it?
- DonaldPShimoda 7y agoIf you look through the other comments here, you'll find plenty of people who didn't know about f-strings prior to this article.
- jwilk 7y agof-strings were added in Python 3.6, released in December 2016. All the other features mentioned in the article, except data classes, are older than that.
- nerdwaller 7y agoAnother useful feature of 3.7+ (also available as a backport by the same name) I’ve not seen mentioned is: ContextVars The gist is you get a single interface for any type of threadlocal storage that also works with coroutines (asyncio). I use it pretty consistently for context logging of long running processes in our systems. However it has implications on other concurrency paradigms usages as well. https://docs.python.org/3/library/contextvars.html https://docs.python.org/3/library/contextvars.html
- whalesalad 7y agoDon't forget @singledispatch! Every once and a while this tool is glorious for a polymorphic handler. Ie, `process_entity` that will fan-out to `process_movie` or `process_tv_show` etc... I miss it in a Python 2.7 project I am on right now. Link to the docs: https://docs.python.org/3/library/functools.html#functools.singledispatch https://docs.python.org/3/library/functools.html#functools.s... It's the same concept as clojure's defmethod.
- dopeboy 7y agoIs type hinting being adopted by Pythonistas today? I've been aware of the feature but haven't used it. To be a modern Python programmer, should I start using it?
- DonaldPShimoda 7y agoI use it everywhere because it vastly improves code readability/usability in my IDE (PyCharm). But I don't know if I'm representative of the general Python population.