278 points · by nekopa · 11y ago · 151 comments
Can anyone recommend some good open source Python software I can look at? I am specifically looking to see ones that employ idiomatic Python, and maybe see how they approach testing (I am not completely new to programming, just rusty after being out of the field for a long time)
Extra bonus points if the software is something you use regularly.
Cheers!
He recommends the following Python projects for reading:
* Howdoi (https://github.com/gleitz/howdoi)
* Flask (https://github.com/mitsuhiko/flask)
* Werkzeug (https://github.com/mitsuhiko/werkzeug)
* Requests (https://github.com/kennethreitz/requests)
* Tablib (https://github.com/kennethreitz/tablib)
Hope that helps---good luck!
However reading the less abstract parts may help. For instance, the paginator is pretty self contained. https://github.com/django/django/blob/master/django/core/pag...
I prefer sklearn like https://github.com/scikit-learn/scikit-learn/blob/master/skl...
A lot of code that does a lot.
Bottle is nice on the web dev front.
The "self.thing = bar" in one function that only gets used in some other function ( or even worse something only used in a companion class) pattern is super prevalent.
Might just be me but I think a lot of the older code suffers from massive locality problems that makes debugging framework bugs super tricky
https://github.com/django/django/blob/master/django/core/man...
Whilst this wasn't a discussion on which framework is best (and I'm not a Web dev by trade either), I must say I turn to Flask, as I find the API more Pythonic.
I guess what I'm trying to say is that the Django source code is probably great, but the less heavyweight packages/frameworks the better. Learn Pythonic API design from somewhere else.
Thank you for this resource, much appreciated!
http://norvig.com/lispy.html http://norvig.com/lispy2.html (Lisp interpreter)
http://www.norvig.com/spell-correct.html (Spelling corrector)
http://norvig.com/sudoku.html (Sudoku solver)
Also his online course Design of Computer programs includes many short, well-explained Python examples:
He's using overly terse, poorly descriptive variable names, not using multiline strings for docstrings, not indenting where he should, and one-lining if/elif statements and function definitions. This style does not contribute to readability.
This is not how I would want someone just learning Python to learn it.
For example:
absolute_path = lambda path: path if path.startswith('/') else '/' + path
To me this is perfectly clearly a simple function whose only purpose is to prepend forward slashes to unix-style paths. Is the following really so much more readable? def absolute_path(path):
if not path.startswith('/'):
path = '/' + path
return path
To my eyes and mind, the second example is not any more readable at the expense of several lines of code. def absolute_path(path):
if not path.startswith('/'):
return '/' + path
return path
This way you don't have to keep track of mutating the path variable. I do find that more readable - it's clearer that there are two paths through the code. That said, this example is trivial enough that I'd probably do it with an inline if/else statement, although still probably not a lambda: def absolute_path(path):
return path if path.startswith('/') else '/' + path
This way it's more obvious at a glance that you're defining a function. It's easier to follow someone else's code if they generally adhere to standards, and Python is a very convention-oriented language.Considering that the creator of the Python language considered getting rid of lambdas because they are essentially limited functions and thus violate Python's "one obvious way to do it" philosophy, I'd rather those learning Python to be shown the latter, rather than the former.
From a development and version control perspective, as soon as the lambda function requires more than a simple expression, i.e. a compound statement (https://docs.python.org/2/reference/compound_stmts.html), you have to trash the whole line, instead of adding perhaps a single extra line of content.
The spellchecker still blows my mind, and I don't yet understand the Sudoku puzzle. We can always take the code and re-format / re-name variables to aid our understanding.
Reminds me of that blog thread where this design pattern guru hemmed and hawed from his high horse over several posts about how to write constrained based solvers and still did not get to a piece of code that actually solved the problem, whereas Norvig just posted a simple solution. A few non-idiomatic indents here and there (although his style has never been a problem for me) are nothing really.
Right.
>Reminds me of that blog thread where this design pattern guru hemmed and hawed from his high horse
I read a similar story a while ago. Two programmers are given the task of writing a program for some non-trivial problem.
One of them, Hoity Toity Harry, tries to apply many of the latest and greatest algorithms, techniques, paradigms, etc., to impress people (of course).
The other, Down To Earth Dan, just strives for a good implementation, with reasonably good algorithms, etc. After a while, Dan finishes his program and does a test run. It works well enough for the task. Meanwhile, Harry is not even near to finishing his code, due to struggling with complexities of the techniques he has tried to use.
The boss comes in, sees the results, and congratulates Down To Earth Dan.
Hoity Toity Harry, of course, has to protest, trying to put down Down To Earth Dan's implementation, saying that it uses simple algorithms, etc., while his own code uses sophisticated, state of the art techniques. Dan replies: "Yes, I could also have used those things. But my program runs, and yours doesn't."
Okay, I changed the programmers' names for fun and effect, but I really did read the story, in some good (and pragmatic) software book, a while ago.
For instance, I find this unnecessarily difficult to read.
>>> 0 if True else 1 if True else 2
0
But breaking it up like this keeps it reasonably concise, while retaining readability.
if True:
a = 0 if True else 1
else:
a = 2
print(a)
They can also be combined with comprehensions, which can be useful.>>> import random
>>> ['a' if random.choice((True, False)) else 'b' for _ in range(6)]
['a', 'a', 'a', 'a', 'a', 'b']
Adherence to Python's best practices / pep-8 are not one of them
I'd rather have Norvig's code solving some IA problem than some perfectly compliant PEP-8 code solving an issue in a naive way
How to make a usable api. The decisions that went into each method call were fantastic. Great test coverage as well. I use package in most python development.
Cheers!
The first thing many users will do is
requests.get?
Which tells them that it takes some kwargs, but doesn't tell them what those kwargs are. It's easy, especially for a newcomer, to read "optional arguments that `request` takes" and fail to understand that they should look up the docs on (not-really-encouraged-as-part-of-public-API) function `request`. That's pretty bad; those kwargs are important! (The reason is because requests.get is implemented as a call to request(method, ..., kwargs) but the user doesn't care what the implementation-level reason is.)Beyond that I did look into the codebase once to investigate a possible bug and there were a few python style things I wanted to fix, but I don't remember them so this comment probably sounds kind of annoying (it would annoy me if I were reading it not writing it...). It didn't strike me a really clean codebase. But yes the library is very useful and I'm sure it's a pretty decent python codebase.
>>> requests.get?
Signature: requests.get(url, params=None, **kwargs)
Docstring:
Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
Here are all the kwargs the user probably wanted to know but failed to find out and was forced to either browse online docs or the source code: def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a (`connect timeout, read timeout
<user/advanced.html#timeouts>`_) tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.ResponseI was using Python for 8 years and IPython for somewhat 5 years if my memory serves me right but today I have learned that you can invoke help on an object by appending '?'. I guess I might delve into IPython documentation sometime.
Thank you for lengthy and detailed explanation.
It's a nice, small, fast web framework. Great for building APIs. Also, it's one ~3k loc, readable file.[1]
[1] https://github.com/bottlepy/bottle/blob/master/bottle.py
- https://github.com/mahmoud/boltons : utility functions, but well documented
- https://github.com/KeepSafe/aiohttp : a Python 3 async HTTP server
- https://github.com/telefonicaid/di-py : a dependency injection framework
- https://github.com/moggers87/salmon : a fork of Lamson (which was written by Zed)
Python's internals are pretty darn open, so here's a few suggestions that push the boundaries of meta programming in Python - they're not the idiomatic code you're looking for right now, but later, when you know the best practices and you're wondering what is possible they'll be good to look at:
- https://github.com/Suor/whatever : Scala's magic `_` for Python
- https://github.com/ryanhiebert/typeset : Types as sets for Python
- https://github.com/AndreaCensi/contracts : Gradually typed Python (akin to MyPy)
- http://mypy-lang.org : Gradually typed Python - the future (at least right now)
It's a little bit meta, but I had lots of "wow" moments. Also, it's a nice example of using C to speed up certain operations.
But I am hoping to move into django eventually, but first I want tknow what is going on behind the curtain.
The functions in PyToolz are short, well tested and idiomatic Python (thought the functional programming paradigm they support is not quite so idiomatic). I recommend starting with the excellent documentation: http://toolz.readthedocs.org/en/latest/
In particular, the API docs have links to the source code for each function: http://toolz.readthedocs.org/en/latest/api.html
Lots of examples of SQLAlchemy, Flask, gevent, and pytest in action to build a REST API and sync platform for email/calendar/contacts data!
On the testing side, I was chatting to a fellow Pyladies attendee about how we do test fixture setup and teardown (especially around databases) -- you might find that interesting to look at too.
(Might not be totally obvious, because the package namespace is called `inbox/` for legacy reasons.)
If a beginner wants to see real production code, rather than toy examples, I think it's inevitable that there will be some points of confusion. Part of the learning process is diving in and exploring and being okay with not totally understanding everything that's going on. :)
If the OP wants to grok a small, discrete codebase then I agree that Django is not what he's looking for.
(Honestly, looking at the repo, I don't even know where to start if I wanted to do a read through. Has anyone created a map? :)
By design, Mercurial has almost no dependencies, so it's very self-contained. I find this makes it a particularly easy codebase to get into.
If you're interested, I would love to walk you (or anyone else!) trough it.
http://dirtsimple.org/2007/01/where-zope-leads-python-follow...
2. The Bazaar VCS is written entirely in Python, is very well documented and has a large test section. (www.launchpad.net/bzr)
Bazaar I may look into, as I know it's a very capable piece of software, and now I know it's well documented with tests makes it very relevant to my interests :)
Edit: I'm on windows, but I'm using vagrant with Ubuntu 14lts image for my development work. Specifically the data science vagrant box...
Disclaimer: contributed to mercurial (and wrote some plugins), wrote few plugins for bzr (it was used in one company I worked for).
P.S. Didn't notice right away, hey, Dirkjan! :)
But honestly, the Bazaar code base is great. Great documentation at every level, and, as far as I can judge, some pretty good code too.
Thank you! (And I had no idea that either bazaar or mercurial were written in Python, because them being 'serious' software I automatically assumed they were written in C. Color me stupid)
It is a minimal web framework like Sinatra or Flask. The beautiful thing about CherryPy is you write code for it the same way you would write general Python code. I enjoy using it for small projects from time to time.
edit:
Bickbucket Repository: https://bitbucket.org/cherrypy/cherrypy/overview
We spent a month of Sundays going through this in the NYC Python office hours. You learn a lot about this object by reading the source, and the WTF per minute rate is fairly low.
The style is also fairly non-controversial.
I fell in love with this project after discovering I don't need ad-choked, dodgy sites to download Youtube videos/mp3s. It also acts as a catch-all downloader for a huge amount of other video hosting sites, despite the name. If you want to learn how to scrape different videos from many platforms, look at this:
https://github.com/rg3/youtube-dl/tree/master/youtube_dl/ext...
It's especially interesting because it takes advantage of new Python features like asyncio.
Cheers!
tornado -
tornadoweb.org
github.com/facebook/tornado
2 - scapy The entire product runs on the python CLI
secdev.org/scapyI referred to it when adding tests for tokenizers in a common lisp NLP application: https://github.com/vseloved/cl-nlp/.
NLTK's value is that it shows you how to write NLP algorithms, and gives you an understandable starting point when you need to do something that nobody has implemented yet.
Rather than seeing the code of great libraries, I sometimes want to see how people use them in the real world.
Also, I second all the suggestions about Kenneth Reitz code, it's wonderful!
[1]: https://github.com/openstack/openstack [2]: https://github.com/openstack/barbican
Seriously, I've seen "sychronization threads" that use no synchronization primitives that have a single bare exception handler trap the critical section. The handler just restarts the computation... leading to fun times.
Cinder also has an interesting problem in the explosion of ABC "mixins" used for constructing a backend driver. It went from 5 in the previous release to something like 25 presently. A patch to fix it: https://review.openstack.org/#/c/201812/
But even the process isn't perfect. I've seen patches that change a couple of log lines get dog-piled with -1 nit-picks about inconsequential wording and take months to get through.
Openstack is an interesting beast but it's not a good example if you're just learning, IMO.
That being said Barbican is quite good, which I think is due to its proof of concept being written in Go[1] before being ported.
If you want to learn decent testing Openstack is a good example, the code as a whole not so much. This also only applies if you want to use unittest or their custom test module, testtools. py.test is a much nicer way to do testing IMO
Thank you for all the good replies peeps!
Cheers!
*Twisted (https://github.com/twisted/twisted)
For async python.
But maybe there are other async python projects that I don't know of. If you know of any please post them, I would also like to learn more about the subject.
https://hg.python.org/cpython/file/3.5/Lib/collections/__ini... Knowing specialized data structure in a language is always important and this is well coded.
Well see the 2 lines I pointed in one of the standard library in python and you will understand that even in good language there will always be dust under the carpet at one point. https://hg.python.org/cpython/file/5c3812412b6f/Lib/email/_h...
But you did teach me one thing, I didn't know that the """ could be used for commenting. I thought it was only for multi-line print statements.
These are exactly the type of things I hope to learn while code-reading.
Cheers!
As ironic(?) as this sounds, where is this doc feature documented?
(Part of my learning is that I am trying hard to learn how to navigate the various Python documentation. For example, I had a hell of a time trying to find a list of format strings, as different sources refer to it as different things)
- https://bitbucket.org/zzzeek/dogpile.core - https://bitbucket.org/zzzeek/dogpile.cache
Thanks for the recommendation.
Cheers!
Still it's a good example how to make many relatively complex parts easily composable and efficient.