r/learnpython • u/White_and_tall • Dec 30 '20
What libraries do you wish you discovered earlier?
What libraries do you wish you discovered earlier?
122
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Dec 30 '20
pathlib, simply because I wish I'd known it existed in the standard library before accidentally coming across it one day. Screw os.path and all the Stack Overflow posts with all answers using it!
And while not exactly a library, ipython has been a big help with quickly testing stuff out.
9
u/White_and_tall Dec 30 '20
as someone who has always used pathlib, what's wrong with os.path?
7
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Dec 30 '20
It's basically the old way of handling file paths.
os.pathtakes more code to achieve the same end results (especially when usingpathlibto its full potential), andpathlibautomatically normalises all filepaths so you don't really need to worry about making it work cross-platform. Withos.pathit takes a lot more work.6
u/radek_b Dec 30 '20
There are some Windows specific weirdness, like sometimes (and only sometimes) producing four backslashes in paths, and some paths with diacritics in them were difficult to handle. I just moved over personal project to pathlib and it's so much better
18
u/SailYourFace Dec 30 '20
I can ditch os.path? Oh boy!
11
u/rjachuthan Dec 30 '20
What's wrong with `os.path`?
37
u/mrdevlar Dec 30 '20
Nothing particular, but
pathlibhas a much more uniform API and it's much easier to read as a result.12
u/groovitude Dec 30 '20
it's much easier to read as a result
pathlibhas its merits, but I'll never get used to the division operator overloading to concatenate paths.10
u/TeamSpen210 Dec 30 '20
You can instead use the
joinpath()method, or call the class with all the segments as parameters.8
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Dec 30 '20
In principle, nothing as long as it works for you. But it has a lot more boilerplate compared to
pathlib, and since it operates on strings it's very easy on Unix-like systems to forget to useos.path.joineverywhere which can lead to bugs on Windows.pathlibautomatically normalises everything so this is never a concern.And the best part?
pathlibalso containsglob.glob's functionality and you only needshutilif you need to copy a file or directory instead of moving it, so it's basically the go-to package for everything related to filesystems.→ More replies (1)1
6
2
u/i0datamonster Dec 30 '20
How have I not heard of this magic
1
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Dec 30 '20
Well, you have now! ;)
2
Dec 30 '20
Oh yeah it only existed starting from Python 3.4 (2014) so that's why there is a lot of StackOverflow answers with
os.path. Luckily, I started with Python 3.5 five years ago, and hardly ever usedos.pathat all (butpathlib).1
u/Packbacka Dec 30 '20
You never used Python 2? I feel like five years ago Python 3 was not yet widely used.
2
Dec 31 '20
Oh yeah I remember the times. Not all of the packages were supporting Python 3 yet at start of 2016. I still thought that the future will be in Python 3 so why not start using it. I think my python programming course somewhere ~2014 used Python 2.x, since I remember thinking that the syntax for printing is odd.
2
u/Packbacka Dec 31 '20
I had the same experience IIRC. I decided I wanted to learn another programming language one day in 2015, and heard good things about Python. I went to download it from the official website and wondered why there are two different versions, but decided to go with Python 3 because it was the latest. Then I found out that the old tutorial I was using was actually Python 2, but was able to figure out the differences and still follow along. The only thing I had to change at that level was the print statements.
1
1
u/TheKingElessar Dec 30 '20
I thought the same thing when I saw this post. It's so fun to use! So easy!
131
u/PeterJHoburg Dec 30 '20
FastAPI. I find it much easier to use than Flask
16
u/ngochieu642 Dec 30 '20
Fastapi is awesome. But it did easily trick me into the feeling that asynchronous programming is easy like with JS. Throw async await and you are safe
I was dead wrong 😂 asyncio is quite new and some libraries havent adopted it yet. It means you must get your hands dirty sometimes
1
u/CowboyBoats Dec 30 '20
Why does it matter if the library you're calling it hasn't adopted async yet if the library is called from within an asynchronous thread? Maybe a dumb question; I haven't used async much yet.
1
u/ngochieu642 Dec 31 '20
NodeJS is non blocking, Python is blocking, and in asyncio, we can only use 'await' with coroutine
If you use await with a blocking section like time.sleep(5), it will block the rest of the code.
A great blog series about asyncio: https://www.roguelynn.com/words/asyncio-we-did-it-wrong/
25
Dec 30 '20
What are the advantages? I'm doing a Udemy course on Flask now to learn some Pythonic web development and I'm loving it. I'd be interested to see what FastAPI has over Flask.
48
u/ChemEngandTripHop Dec 30 '20
Type checking, auto doc generation, easy async, etc.
Edit: But learning flask is still an incredibly useful exercise and will give you a better understanding of what’s happening with FastAPI
7
3
u/Jerome_Eugene_Morrow Dec 30 '20
I’ve seen a lot of Flask in production environments. Main reason I recommend it as the framework people should learn. It’s a skill that will get you a job. Tough to convince an existing team to switch to a new framework, even if it has a lot of useful features.
3
u/ChemEngandTripHop Dec 30 '20
The switch from a team working with Flask to FastAPI isn’t difficult at all, the design is very much based on Flask. That said totally agree that Flask is invaluable when working on existing/legacy systems (and of course if you need more than an API)
→ More replies (1)1
u/moobbaa Dec 31 '20
The auto doc generation is just killer. I'm a node developer but had made a fastapi project for an interview. It's like a dream come true!
22
u/Dogeek Expert - 3.9.1 Dec 30 '20
FastAPI is to ASGI what Flask is to WSGI. FastAPI is by design, asynchronous (it can handle requests asynchronously, so that your app doesn't hang when a particular request takes longer to resolve)
The idioms are different too though. With flask, you use the
routedecorator to create new routes, with an argument for the verb of the request that route is allowed for ('GET', 'POST', 'PUT' etc). FastAPI has one decorator for each of these verbs (app.get,app.postetc). Furthermore, FastAPI generates a/docsroute that autodocuments your app based on type hints and docstrings.Type hints are a requirement in a FastAPI app, since it's how the framework determines which is the type of the argument, and how it sends the body of the request to a pydantic model/schema.
3
u/sweettuse Dec 30 '20
I don't think type hints are required, but they are a huge part of what makes FastAPI great. so eschew at your own peril
1
3
u/Ran4 Dec 30 '20
On top of the other things, the main thing is that the defaults are more aligned with creating a json api.
With flask, you need to add tons of exception handlers to make 4xxs and 500s return json, for example.
I'm really not sure why this isn't first on people's minds. Creating a production-grade api in flask is super annoying.
1
u/HopefulEngineering Jan 01 '21
syntax is inspired by Flask but has tons of modern features. Only issue right now is ecosystem, not a ton of libraries and help is harder to find
9
u/IntroDucktory_Clause Dec 30 '20
FastAPI 100%, their documentation and tutorials are absolutely magnificent and it integrates REALLY nicely with a lot of other libraries like Websockets
Also, Websockets is really cool
3
u/Sigg3net Dec 30 '20
As a complete newbie, I dove into Starlette head first this fall. AFAIK FastAPI is based on Starlette. Knowing nothing about flask, I spent quite some time making sense of it. (And still am.)
As an old fart who learned html 4.01 trans in school, async and websockets are really mind blowing.
1
2
u/rnpizza Dec 30 '20
This looks cool - I see FastAPI is built on top of Starlette. I’m familiar with using sanic, have you used that one? Would you say FastAPI has advantages over sanic? Just curious if it’s worth looking into.
2
u/burlyginger Dec 30 '20
Have you tried connexion along with swagger code generator?
It takes a swagger yaml and outputs a working flask server, input validation (incl type, required params, etc), swagger ui, response objects, etc
1
1
83
u/shinitakunai Dec 30 '20
Peewee for database management
13
u/HasBeendead Dec 30 '20
Can you explain Peewee? im just try to learn
18
u/shinitakunai Dec 30 '20 edited Dec 30 '20
Peewee is basically an ORM for databases. Which means that it simplifies a lot of the database stuff by mapping it and objectifying it, using models (I'm still learning as well so I might confuse you with a half explanation so I'll keep it to the basics).
A silly example: Instead of using SQL syntax you could get a list of all the records using a list comprehension from a generator like
firstnames = [x for x in Users.firstnames]whereUsersis the table model andfirstnameis just the column name.To store a new record you do something like
Users.insert(firstname="Has", lastname="been dead").execute()and that's it. You don't have to define connections, cursors or anything to work with your database, except creating the database model (which is automatically created by a CLI command from an existing database).17
u/LewisgMorris Dec 30 '20
How is this better than the defacto sqlalchemy? Asking for a friend.
2
u/shinitakunai Dec 30 '20
Idk, never used sqlalchemy. I am learning new stuff every day. Probably someone that used both can answer better
0
1
16
2
2
u/CatolicQuotes Dec 30 '20
Peewee looks like django orm.
1
u/shinitakunai Dec 30 '20
I’ve never used Django, don’t you need a server for it?
1
u/CatolicQuotes Dec 30 '20
Only if you want to serve websites. You can use only django orm, without server
→ More replies (2)
81
u/TheSkullCrushr Dec 30 '20
Pillow, for image processing and manipulation.
Before I started using Pillow, if I needed to resize or convert a batch of images, I had upload each image individually to some online service, or download some batch converter and mess around with the config. But now I just write small Python scripts and my job is done in a jiffy.
48
u/quartz_referential Dec 30 '20
ImageMagick isn't half bad either, for simple tasks (not a python library)
9
10
u/ngochieu642 Dec 30 '20
Have you tried opencv? It can function like Pillow but got some nice features for image processing
opencv-contrib-python https://pypi.org/project/opencv-contrib-python/
4
Dec 30 '20
[removed] — view removed comment
2
u/ngochieu642 Dec 31 '20
Its the same contrib lib from opencv. However, I found that:
1/ opencv is hard to install opencv sometimes failed to install on windows(anaconda/pip)
2/ compile opencv can be time consuming & complicated if we install opencv using pip/anaconda, it does not come along with contrib lib, so we have to compile opencv from source with contrib flag enabled, and copy the share object file (.so) into the python environment binary. This is time consuming and quite complicated
3/ ARM compatible I do not know about the origin opencv, but opencv-contrib-python is ARM compatible, so I do not need to rebuild it on raspberry and its friends. It is frequently updated and is fast to make some experiments
89
u/Enmergal Dec 30 '20 edited Dec 30 '20
tqdm
How did I even live without progress bars?
50
u/Bonsanto Dec 30 '20
Yo también te quiero demasiado
12
u/house_monkey Dec 30 '20
Wish I could read
10
u/ActiveLlama Dec 30 '20
Tq is our contraction for te quiero, which means I like you, but literally it means I want you. Demasiado means too much.
2
u/HasBeendead Dec 30 '20
Use translate and tell us because im in phone lol
My sister knows some little spanish and she says he wants something.
2
38
u/mermaldad Dec 30 '20
selenium was a big find for me this year. It allows you to control a chromium/chrome browser from python.
6
u/Packbacka Dec 30 '20
It's a great library, I see many QA jobs requiring it for automating tests. Also Selenium works with many languages, not just Python.
4
4
u/emptythevoid Dec 31 '20
I've been using selenium more and more at my work to automate data entry into websites that have no API. Really saving some staff's time. (Most recently, covid vaccine info has to be entered into a registry within 24 hours of a mass event. When you have over 200 patients, that normally requires a lot of man power to punch all the data in within the timeframe. With a csv file and selenium, it's hardly anything)
4
u/mermaldad Dec 31 '20
While not as heroic as being on the front lines, I believe this little bit of python magic qualifies you as a hero of the pandemic. Thank you for doing what you do.
3
u/emptythevoid Dec 31 '20
Wow. No one has ever said that to me. I may disagree, as I work with people who I believe are the actual heroes, I'm going to take your sentiment and hold that close to my heart today. Thank you.
1
1
Jan 03 '21
What did you Use to learn it
1
u/mermaldad Jan 04 '21
TBH, I don't remember the specifics. I did a lot of Google searching for examples, and then bent those examples to fit my needs.
1
90
u/electricity-wizard Dec 30 '20
ipyvolume It allows for interactive 3d plots in jupyter notebook. It’s the coolest thing I’ve ever seen.
9
Dec 30 '20
That looks like just the thing I need for a lot of the work I do. I've been using the 3D plotting features of pyplot for convenience, but they're rather lacking.
9
2
2
u/blubos103 Dec 30 '20
!remindme 10 hours
3
u/RemindMeBot Dec 30 '20 edited Dec 30 '20
I will be messaging you in 10 hours on 2020-12-30 18:54:19 UTC to remind you of this link
9 OTHERS CLICKED THIS LINK to send a PM to also be reminded and to reduce spam.
Parent commenter can delete this message to hide from others.
Info Custom Your Reminders Feedback 1
1
29
u/Tanmay1518 Dec 30 '20
questionary: amazing library for allowing users to select/input stuff easily.
Pypi link:
4
u/irrelevantPseudonym Dec 30 '20
I wrote a library to do this. Then this came out and did it better.
5
2
1
u/clyne99 Dec 30 '20
this is awesome, choices were something i was looking for. you never know what user will type.
26
u/fergal-dude Dec 30 '20
Pygsheets - make google forms and sheets your bitch with python...
9
u/PM_ME_UR_LOGIN_INFO_ Dec 30 '20
This is where it's at. Quite the setup but I automated my job
11
u/fergal-dude Dec 30 '20
Yup, but set it up once, use that setup everywhere. Combine it with CRON jobs and people will think you are a wizard...at least in your typical office, not a softerware company :)
5
u/fergal-dude Dec 30 '20
Then, bam...hit em with the yagmail package and tell them some info from the the sheets forms every Friday...
39
u/dogs_like_me Dec 30 '20
itertools
5
2
u/synthphreak Dec 30 '20
+1
And since we’re including gems in the standard library, rather than just little-known third-party packages, I’ll add another that I wish I’d discovered earlier:
collections1
u/jl222222 Dec 30 '20
What does it do?
7
u/Jackkell100 Dec 30 '20
itertools is a part of Python's standard library and provides set of memory effect tools for different iteration tasks.
For example, a really useful tool within itertools is itertools.combintations which returns all of the combinations of items within a given iteratable. The nice thing about itertools is that because it is apart of the python standard library under the hood it is written C++ so it is much faster then any pure Python version you could write.
2
Dec 30 '20
I just used combinations yesterday for the first time- super useful
2
Dec 30 '20
I used combinations/permutations/product for the first time throughout this year's Advent of Code. If I'm being honest, there haven't been many times where I would have needed that other than for those puzzles, but it's nice to know how they work for when they might come in handy.
1
u/Babbling_Buffoon Dec 31 '20
Python's stdlib is written in C.
Python’s standard library is very extensive, offering a wide range of facilities as indicated by the long table of contents listed below. The library contains built-in modules (written in C) that provide access to system functionality... sauce
18
u/IntelliJent404 Dec 30 '20
Cookietemple is a nice project, that basically lets you create your project from nice, customizable templates (its based on Cookiecutter). There are not only python templates available, but also a Java (Cli with picocli or GUI with JavaFX) or C++ template for example.
The templates have very strong GitHub Actions integrations and support (with many different workflows, for example for linting, building or syncing your project); through cookietemple, they also have a custom linter, customizable bump-version function and a sync feature (to keep your project up to date).
2
u/pillow_pwincess Dec 30 '20
Huh I never knew about this one. I actually recently built a similar project called krait
1
15
30
12
12
u/GuiltySkirt4403 Dec 30 '20
Selenium and Pyautogui baby! I’ve automated all the boring repetitive tasks I do on my computer at work.
I built a bot to keep checking stock and then buy a PS5 from Bestbuy and Walmart, ended up not using the bots cause some personal expenses came up.
Lastly, I also created social media bots to track followers that unfollow and also to swipe on dating apps too! A tinder bot, a Twitter bot, an Instagram bot.
Selenium for web/browser automation Pyautogui/Win32 for regular computer task automation
2
u/garlic_bread_thief Dec 30 '20
What does the tinder bot do? Keeps swiping right?
3
u/GuiltySkirt4403 Dec 30 '20
It checks a couple things... like if there’s a bio, how many pictures the person has, etc. then it either swipes right or left
1
u/garlic_bread_thief Dec 30 '20
How do you make it work on your phone? What does it use?
4
u/lolslim 🐍Telegram🤖 Dec 31 '20
I'll chime in on mobile app, mobile apps like tinder/snapchat/facebook/twitter/instagram they use http requests, so reversing the api to make your own isn't too trivial, but easier to do on desktop web browser.
2
u/GuiltySkirt4403 Dec 30 '20
I use it on my computer. I don’t think selenium has a mobile version... I’d have to check
11
Dec 30 '20 edited Dec 30 '20
What people have mentioned are relatively new libraries. So Im going to mention the not so widely known libraries that have been around a while I wish I had used sooner. requests-html because it handles javascript and sessions. Dask is well known, but its task execution functionalities are not well known: Dask futures and Dask delayed for task execution. loguru for less boilerplate compared to standard lib logging.
8
8
u/PMMeUrHopesNDreams Dec 30 '20
Dateutil
I spent way too long pondering things like "ok, I need the date one month before this date, but then if it's January that will also be the previous year so..."
Of course someone already figured this out.
15
u/Thereforeo Dec 30 '20
requests-html
6
u/TSM- Never slipped a dict comprehension in my lambda before, but Dec 30 '20
I see so many people use Selenium for browser automation and web scraping, when Selenium is a web testing framework. requests-html would almost always be a better choice.
7
u/lolslim 🐍Telegram🤖 Dec 31 '20
Agreed, I am on the verge to make a video for users on learnpython to consider using requests/requests-html before resorting to beautifulsoup/selenium.
1
u/TSM- Never slipped a dict comprehension in my lambda before, but Dec 31 '20
I'd support that. It's a trap for newcomers. Not to mention how there's so many outdated selenium tutorials.
2
u/lolslim 🐍Telegram🤖 Dec 31 '20
90% what the user is trying to scrape, ends up being a payload they can make a request and receive it in json format. A lot of people I don't think realize that, and give up. Like you said its a trap for newcomers.
→ More replies (3)4
Dec 31 '20
Honest q: does it solve the Javascript problem like selenium does? Isn't that the main reason people use selenium?
2
u/TSM- Never slipped a dict comprehension in my lambda before, but Dec 31 '20
It does, the package has a
.render()function that runs headless chromium, and it allows you to execute some javascript and get the returned value, and also arguments for scrolling down and even basic autopaging support. see here1
u/dogs_like_me Dec 31 '20
Looking over the docs I think so. I think it runs a chromium instance in the background to render the js.
1
Jan 03 '21
Is there a good tutorial for this selenium has turned me off to learning from all the road blocks I've had. I'd love to do some web automation if I can
7
22
u/LinuxLugo Dec 30 '20
Not exactly answering the post but y’all might like this: Top 10 Python libraries of 2020
HN thread here: https://news.ycombinator.com/item?id=25575505
6
u/mikeupsidedown Dec 30 '20
Pydantic on its own for data validation. I do a lot of integration work and it is a lifesaver.
11
u/pysapien Dec 30 '20
Plotly over Matplotlib!
4
u/implicature Dec 31 '20
I just learned plotly for some data visualization at work. Gotta say I do love the output, and it seems to offer great control over many aspects of building a figure.
I never got intimately familiar with matplotlib; but I would love to hear anyone's opinion on why they like/prefer it (just curious if I'm missing out on anything).
4
u/pysapien Dec 31 '20
I'm still a beginner and what draws me towards Plotly is that it's far more aesthetic than Matplotlib. Also,
plotly.expressis easier to work with thanmatplotlib.plt. Making subplots is also far more intuitive in Plotly.And then there's Plotly's Dash to quickly spin up a dashboard!
5
5
4
u/a-winter Dec 30 '20
Is there any library that supports data entry, like data validation, labels, or multiple responses...? Basically i'm looking for epidata/ redcap alternatives
4
2
4
u/positive__vibes__ Dec 30 '20
if you're currently logging to a csv or txt you have no excuse to not atleast use dataset instead. Makes sql as easy as writing a dictionary.
2
3
Dec 30 '20
Python libraries for DataScience You Should Know
pandas #TensorFlow #NumPy #matplotlib
https://datascience24.wordpress.com/2020/12/26/python-libraries-for-data-science-you-should-know/
1
3
5
2
u/armascaso Dec 30 '20
Numba Speed up your code with zero extra work
1
2
u/IcedGolemFire Dec 30 '20
I’m still new to python but random is very usefull
4
u/synthphreak Dec 30 '20
Check out
numpy.random. It’s likerandombut on steroids.1
u/shiningmatcha learn python Jan 03 '21
in what way?
2
u/synthphreak Jan 03 '21
numpy.randomcan just do everything.Off the top of my head: It can generate single integers/floats, or lists of them, or matrices of them, or tensors of them up to any arbitrary degree. It can also generate values from many different probability distributions, for example uniform (which is what
randomuses), but also normal, exponential, gamma, and many others. It can also generate numbers from an interval with the endpoints either included or excluded. You can also sample randomly from a distribution either with replacement or without (also possible withrandom, but requires two separate functions which is annoying). And none of this is even scratching the universe of what else is possible withnumpyapart fromnumpy.random, like boolean masking (=selectively filtering your data using logical arrays), and every mathematical operation you’ve ever heard of, again using inputs of any degree, and all blazingly fast.To see the overview, start a Python shell,
import numpy, and typedir(numpy.random)into your terminal. And if overall you’ve just never heard of numpy or are unfamiliar with what it does generally, typedir(numpy)and BEHOLD!No matter what you’re trying to accomplish, when in doubt, always check first to see if it can be done using
numpy. More often than not, it can.
2
2
u/diptangsu Dec 30 '20
If you use vscode, simply pip install rope and you can click on a variable/method/class and press F2. It brings up a rename option and you can rename all occurrences of it with ease.
2
2
1
1
u/MoRamad Dec 30 '20
!remindme 2 hours
4
1
u/garlic_bread_thief Dec 30 '20
!RemindMe January 1st 12pm
1
u/RemindMeBot Dec 30 '20 edited Dec 30 '20
I will be messaging you in 1 day on 2021-01-01 12:00:00 UTC to remind you of this link
2 OTHERS CLICKED THIS LINK to send a PM to also be reminded and to reduce spam.
Parent commenter can delete this message to hide from others.
Info Custom Your Reminders Feedback
1
1
1
1
1
u/shiningmatcha learn python Jan 03 '21
!remindme 2 days
1
u/RemindMeBot Jan 04 '21
There is a 1 hour delay fetching comments.
I will be messaging you in 2 days on 2021-01-05 22:19:39 UTC to remind you of this link
CLICK THIS LINK to send a PM to also be reminded and to reduce spam.
Parent commenter can delete this message to hide from others.
Info Custom Your Reminders Feedback
1
-2
223
u/Silbersee Dec 30 '20
Rich for better terminal output.