All posts by Wyatt

PEP 420 Namespace Packages – Somewhat Surprising

Update 2014/03/16: I submitted a better different patch, which was partially merged, but there’s still an ongoing discussion about the best way to make find_packages() support PEP 420.

Earlier today I submitted a patch to setuptools that adds support for PEP 420 namespace packages (“NS packages”) to find_packages(). In the process, I learned a few things about NS packages that I found somewhat surprising.

My initial “intuitive” understanding was that only directories with either one or more .py files or containing only directories would be considered NS packages. I also thought that NS packages couldn’t be nested under regular packages (i.e., those with an I’m not exactly sure how I arrived at this understanding, but it’s what seemed to make sense before I dug into this.

The first thing I found surprising is that NS packages can be nested under regular packages. I couldn’t figure out what the use cases for this would be (which, of course, doesn’t mean there aren’t any). One potential problem with this is that if you have a directory with package data that’s not a Python package, it can be imported as a package, whereas in the pre-420 days you’d get an ImportError.

The second surprising thing, which is a generalization of the first, is that any subdirectory of a directory that’s on sys.path can be imported as an NS package. This is probably useful in certain scenarios, but it can also cause issues in other scenarios.

For example, if find_packages() emulated the above behavior, by default *every* subdirectory in a source tree would be considered a package and included in the package list and therefore in a distribution, which is often (maybe usually) undesirable.

If you’re using vanilla distutils, this isn’t an issue since you have to explicitly list all of the packages in a distribution, but that can be super tedious and it’s easy to forget to add new packages to setup(), and a lot of packages on PyPI already use find_packages().

So I had one thought that an explicit __not_a_namespace__ marker file could be added to directories that shouldn’t be considered NS packages (or maybe __package_data__ is a better name). This is almost certainly a non-starter though, because it could lead to a lot of empty files cluttering up your source tree (plus, you might forget to do this too, so it doesn’t really help with that aspect).

My patch for find_packages() adds the ability to explicitly specify the packages you want to include using wild card patterns. In the following example, the mypkg directory and all of its subdirectories will be included as packages (when running Python 3.3+):


from setuptools import setup, find_packages


This goes part of the way toward making sure only the appropriate directories are included as packages in a distribution. In simple cases, it will be sufficient by itself. In other cases, it might be necessary to exclude certain directories:


This is a bit more complex than the way things used to be–where you could almost always simply say packages=find_packages() without thinking about it–but I guess that’s the price of new features and functionality.

Update: I thought of a little hack for explicitly marking non-package directories–name them with an extension (e.g., They will then become unimportable, and find_packages() already skips directories with dots in their names.

Travis CI, Python 3.3, Buildout

I had the hardest time configuring Travis CI for several Python 3.3 packages. I think it may have been because they’re all PEP 420 namespace packages. The strange thing is that the tests would pass for some of the packages but not others.

I ended up creating a package (which I lovingly named travisty) so my repos wouldn’t be cluttered with hundreds of superfluous commits recording my failed attempts to get things working. I got pretty frustrated and almost gave up on Travis entirely.

There was a post on Planet Python recently about problems with Python 3 and virtualenv, and I’m guessing the issue is something related to that and not Travis specifically, but I never did actually figure it out.

Instead, I tried installing my packages using Buildout (which I prefer over virtualenv for development anyway), and that magically worked. It kind of bugs me that I don’t know why it works and the bare virtualenv doesn’t, but at this point I’m just happy that it does.

Here’s the .travis.yml I ended up with:

language: python
  - "3.3"
  - pip install zc.buildout
  - git clone git:// ../tangled
  - buildout
  - ./bin/tangled test

The tangled test script is just a tiny wrapper around the built in unittest discovery. It’s equivalent to ./bin/python -m unittest discover my/package.

What I Hate About Python

During an interview a while back, I was asked to name some things I hate about Python. For some reason, I choked and couldn’t think of a good answer (I kind of wanted to blame the interview process, but that’s a rant for another time).

Maybe I’ve just been programming in Python for too long, and that’s why I couldn’t think of something (or maybe I’m just a massive Python fanboy). On the other hand, I’ve been programming in JavaScript (which I generally like) for about as long, and I can think of at least a few things right off the top of my head (mostly related to weak typing).

I did a search to see what other people don’t like about Python to get some inspiration, but I didn’t come across anything I truly hate.

Things That Don’t Bother Me

  • Significant whitespace. I love it.
  • Explicit self. I guess it would be “convenient” if I didn’t have to add self to every method signature, but I really don’t spend much time on that, and it takes about 1ns to type (in fact, my IDE fills it in for me). There are technical and stylistic considerations here, but the upshot for me is that it just doesn’t matter, and I actually like that all instance attribute access requires the self. prefix.
  • “Crippled” lambda. There are rare occasions where I want to define more complex anonymous functions, but there’s no loss of expressiveness from having to use a “regular” named function instead. Maybe multi-line anonymous functions that allow statements would lead to different/better ways of thinking about programs, but I’m not particularly convinced of that. (Aside: one thing I do hate relating to this is the conflation of lambdas and closures–normal functions are closures in the same way that lambdas are.)
  • Packaging. I don’t know why, but I’ve never had any problems with setuptools. There are some issues with the installation of eggs when using easy_install, but I think pip fixes them. I am glad that setuptools is now being actively developed again and the distribute fork is no longer necessary.
  • Performance, GIL, etc. I’ve used Python for some pretty serious data crunching (hello, multiprocessing) as well as for Web stuff. There are cases where something else might have been faster, but Python has almost never been too slow (caveat: for my use cases). Of course, Python isn’t suitable for some things, but for most of the things I need to do, it’s plenty fast enough.
  • len(), et al. I don’t have anything to say about this other than it’s a complete non-issue for me. Commentary about how this means Python isn’t purely object-oriented makes me a little cranky.

Things That Bug Me a Little Bit

  • The way super works in Python 2 is kind of annoying (being required to pass the class and self  in the super() call). This is fixed in Python 3, where you can just say super().method() in the common case.
  • Unicode vs bytes in Python 2. This is also fixed in Python 3 (some people have argued that it’s not, but I haven’t run into any issues with it yet (maybe it’s because I’m working on a Python 3 only project?)).
  • The implicit namespace package support added in Python 3.3 causes some trouble for my IDE (PyCharm), but I’m assuming this is a temporary problem. I also had some trouble using nose and py.test with namespace packages. Again, I assume (hope) this is only temporary.

Things That Bother Me a Little More

  • The Python 2/3 gap is a bit troublesome. Sometimes I think the perception that there’s a problem may be more of a problem, but I don’t maintain any major open source projects, so I’m not qualified to say much about this. Personally, I’ve really been enjoying Python 3, and I do think it offers some worthwhile advantages over Python 2.


There isn’t one. I left some things out intentionally (various quirks). I probably forgot some things too.

I’m Working on a Python 3 (only) Web Framework

I’ve been working on a Python 3 (3.3+) only Web Framework for the past few weeks. My initial motivation was to try to build something “RESTful” that doesn’t use the concepts (or terms) “view” or “controller” at all.

That’s because I don’t even know what a “view” is (or is supposed to be be). I’ve tried to think of views as “representations” (i.e., in the sense of representing some data as a particular content type like HTML or JSON), but in the real world view functions are often used to implement business logic, and the term “view” seems misleading (“action” seems more appropriate in this case). The term view is also used by some frameworks to refer to templates (e.g., Rails), and this usage actually makes a bit more sense to me.

If you’re just throwing some code together, maybe this type of thing doesn’t matter too much, but when things get complex (as they tend to) and you’re looking for ways to keep things simple (in terms of concepts, code organization, etc), I think it can make a big difference. Your core abstractions inform (and possibly limit) your thinking; they can also limit, to an extent, what’s possible or at least easily doable.

A different way to say this is that “views” and “controllers” don’t really fit my brain, so I’m experimenting with something different. I actually tried to implement something like this on top of Pyramid at one point (pyramid_restler), but I got hung up trying to build on top of views (although it’s still useful, IMO).

So, I set out to create a new framework that uses resources and representations as its main abstractions. Resources are things that are mounted at a particular path, respond to HTTP methods, and return data that gets represented according to the requested content type (i.e., as specified by the Accept header (note to self: should look at Accept-* headers as well)).

I’ve also put some effort into making the framework “correct” in terms of HTTP status codes and other RESTful concepts. But I’m finding that it’s not so easy to create a general purpose framework that handles every scenario right out of the box. For example, it’s okay (according to the RFC) to return various status codes for a POST or a PUT depending on the circumstances, so you can’t just say, “Oh, it’s a POST, so we’ll automatically return a 201 Created.”

I’m not sure how to completely generalize HATEOAS either. For certain scenarios you can say things like, “This container resource has these items, so generate a set of links to the items and include that in the representation.” But I’m not sure how you could cover every link scenario in a generic manner. If certain constraints are enforced, maybe… (maybe I just haven’t thought hard enough about this…)

That said, I think it’s possible to create a framework that at least nudges people in the “right” direction (or at least a particular direction).

So that’s the gist of it. As it matures, I plan to post more about it (including links to the source, which will be MIT licensed). For now, I’m mostly avoiding the term RESTful and just calling it resource-oriented.

Python 3

This is the first project that I’ve really used Python 3 for, and it’s been fun playing with all the shiny new stuff (hello, built in namespace packages). I was planning to say more about the choice of Python 3 (3.3+ in particular) in this post, but I think it’s gotten a bit long already. I’ll be writing another post about that soon, including the issues I’ve run into (or lack thereof).

Generating Random Tokens (in Python)

Update 1/13: After reading the comments and thinking about it some more, I think binascii.hexlify(os.urandom(n)) is the easiest way to generate random tokens, and random = random.SystemRandom(); ''.join(random.choice(alphabet) for _ in range(n)) is better when you need a string that contains only characters from a specific alphabet. Pyramid uses the former approach; Django uses the latter.

I’m working on a web site where I need to generate random CSRF tokens. After digging around a bit, I found os.urandom(n), which returns “a string of n random bytes suitable for cryptographic use.” Okay, that sounds good… except that it can include bytes that aren’t “web safe”.

So I needed a way to encode the output of urandom. I poked around some more and saw binascii.hexlify(data) being used for this purpose (in Pyramid). For some reason, though, I thought it would be “clever” to hash the output from urandom like so: hashlib.sha1(os.urandom(128)).hexdigest().

What I like about this is that no matter how many bytes you request from urandom (assuming more bytes means more entropy), you always end up with a 40 character string that’s safely encoded.

I’m not sure if this provides any real benefit though (in terms of increased security). Are there better ways to generate random tokens?

Another thought I had was to use bcrypt.gensalt() and use its output as is–it uses urandom to generate the initial salt, which is then hashed, and also returns a fixed number of bytes (29).

On a slightly related note, I recently needed to generate a new PIN. My first thought was to reuse a PIN I use elsewhere, but of course that’s a bad idea. My second thought was to use KeePassX to generate one. I happened to have a calculator sitting next to me (one with big buttons); I closed my eyes and banged on it a bit to generate the PIN.

Wildwood Trail from Germantown Road to Newberry Road

Date: July 17, 2012
Elevation: N/A
Distance: 11
Time to top: 1 hour 30 minutes
Time back: 1 hour 20 minutes
Weather: Partly cloudy, not too hot
Gear: Running shoes, small Camelbak pack with 3 liters of water

This was a nice, rolling hike through the northern part of Forest Park. This section is all forested except for two (?) clearings that take about thirty seconds to traverse. There’s no significant elevation change to speak of, though there are a couple of moderately steep sections.

Wildwood Trail, Newberry Road trailhead

Angel’s Rest

Date: July 15, 2012
Elevation: ~1500 feet
Distance: 4.4 miles (+2)
Time to top: 45 minutes
Weather: Overcast mostly, intermittent light rain on the way up, fog at top, a bit of sun on the way down
Gear: New hiking boots, medium pack, 2 quarts of water, rain jacket

There was steady rain on the drive out, which was good because that meant there’d probably be less people on the trail. There were still quite a few people out, though–this is probably not a good place to go on a sunny weekend.

I initially missed the Rest because of fog–I couldn’t see the view–and walked an additional couple miles beyond it before I realized I went too far. I found a nice patch of huckleberries, though, so it was worth it (especially because I didn’t bring any food!). First I went down the trail toward Multnomah Falls, then I turned back and went up another trail toward Devil’s Rest.

Once I finally got to the Rest, I hung out for an hour or so and watched the fog. At some points, it was a little creepy–I was by myself and the fog seemed alive. Now and then the Columbia river and WA were visible.

Most of the time, it looked like this:

View from Angel's Rest

But I did get one good shot from the top:

Clear view from Angel's Rest

Saddle Mountain

Date: July 11, 2012
Elevation: 3283 feet
Distance: 5.4 miles
Time to top: 50 minutes
Weather: Hot (~90 degrees), sunny, hazy
Gear: Trail running shoes, small Camelbak pack

The trail is very steep pretty much the whole way; it’s shaded for about the first half and then open and rocky to the top. It was really hot, and I got a bit sunburned. The view from the top would probably be pretty spectacular on a non-hazy day.

View from Saddle Mountain

There’s a nice, shady spot to hang out at the end of this other trail (top left of image below), which is just a little lower than the peak. I hung out there for about an hour.