import – complex or complicated?

In Python, life is really easy when all your .py files are in one directory. The moment you want to organize your code into folders there’s a wall of challenges you have to climb. I believe this is an issue that can be alleviated with one small fix.

Here’s a comparison of how a developer shares code across a project in C/C++ and Python:

C/C++ Python
Forms #include <from_env_dirs_first>
#include “from_local_dir_first”
#include “abs_or_rel_file_system_path”
import module
import module as alias
from module import var
from module import *
from ..package_relative_path import module
from package.absolute_path import module
try:
    import one_thing
except ImportError:
    import another as one_thing
Namespacing Public toilet – everything included is global. “Namespaces are one honking great idea — let’s do more of those!”
Seriously, module encapsulation is fantastic.
Helpful extra knowledge Makefiles/vcproj configurations of paths
#ifdef
sys.path
__all__
__path__
Mandatory extra
knowledge (“Gotchas”)
#pragma once (or the equivalent #ifdef)
certain things aren’t allowed in .h files
please don’t use absolute paths
__init__.py
syntax for intra-package imports
modules intended for use as the main module of a Python application must always use absolute imports.

Now this isn’t an exhaustive list as I want to discuss just a small subset from the above table. Also note that I didn’t go into “ctypes”, “#pragma comment(lib…)”, etc. as we’re talking about sharing code, not binaries.

For the 6 years of keyboard tapping I’ve done in C and Python, I never once was confused as to how to access code between directories in C; Python on the other hand has gotten me quite a few times and I always need to rertfm. And I consider myself far more interested and fluent in Python than in C/C++. This may be just a problem with my head, but I’d like to vent either way.

Blah, blah, what’s the problem?

Skip this section if you’ve already had experience with said problem, I’m sure it’s as painful to read as it was to write.

Python has this really elegant solution for one-folder-mode, “import x” just gives you what you expected, either from the standard library (sys.path, etc) or your local directory. If you have “os.py” in that local directory then you shadow out the standard “import os”. Once you mix directories in there, python is suddenly afraid of shadowing and you can’t import things from a folder named “os” unless it has an “__init__.py”. So shadowing here is allowed and there not. If you want to access modules from the outside (dot dot and beyond), then you have to be in a package, use sys.path, os.chdir or maybe implement file-system-imports on your own.

Personally, I find myself doing this design pattern a lot:

  1. The App directory
    1. main_app_entry.py
    2. framework
      1. general_useful_things.py
      2. more_frameworkey_goodness.py
    3. components
      1. this_solves_a_problem.py
      2. another_tool.py

I usually have an “if __name__ == ‘__main__’:” in my modules and there I have some sort of test, utility function, or a train of code-thought not yet organized.

How can another_tool.py access general_useful_things.py? First things first – __init__.py everywhere! After trying a few ways to do the import – here are a few results.

So what’s needed for another_tool to import general_useful_things:

  • “from framework import general_useful_things” works in another_tool.py if we only use main_app_entry.py, it does not work if we run another_tool.py directly. Does this mean __name__ == “__main__” is a useless feature I should ignore?
  • Here’s the rest of the list of failed attempts:
    #from app.framework import general_useful_things
    #from .app.framework import general_useful_things
    #from ..framework import general_useful_things
    #from .framework import general_useful_things
    #from . import framework
    #from .. import framework
  • And this little recipe works in most cases:
    SRC_DIR = os.path.dirname(os.path.abspath(__file__))
    os.sys.path.append(os.path.join(SRC_DIR, '..', 'framework'))
    import general_useful_things

If you want to tinker around with that example directory structure here you go: http://dl.dropbox.com/u/440522/importing%20is%20hard.zip

Python doesn’t have file-system imports

To summarize my rant – python has this mantra that your import lines should be concise and thus a complex searching import mechanism was built to avoid filesystem-path-like imports. The price we pay for that searching import mechanism is that you really need to learn how to use its implicit kinks and even then it’s not that fun to use.

The theoretical ideal solution

“import x” always imports from sys.path etc, if you want to import something local you use “import ./local_dir_module”, the forward slash signals the parser and the developer that a file-system import is taking place. “local_dir_module.py” needs to be in the current folder for the above example to work. Just in case it isn’t clear, the module “local_dir_module” will be accessed as usual, without the “.py”, dots or slashes. The import statement is the only place where slashes are allowed and the result of the import is a module in the stater’s namespace.

That’s as explicit, simple, concise and useful as it gets.

The practical solution

I don’t mind if “import x” still works as it does today, the main point is that now you can do things like “import ../../that_module_from_far_away”. So you can actually keep python 100% backwards compatible and still add this feature.

Concerning the backslash/forwardslash debate – I’m a windows guy and I don’t mind using the forward slash for Python, Windows doesn’t mind it either (“/” only fails in a few specific scenarios like cmd autocomplete). Another fun fact is you can avoid littering your app with __init__.py if you aren’t going to be accessed using that big old search-import-package mechanism.

I realize this whole fiasco might raise the question of absolute path imports, in my opinion these shouldn’t be allowed. Absolue includes in C/C++ destroy portability, impose annoying folder structure constraints and they’re ever-so tempting at late hours where you don’t really want to calculate the amount of “..” needed. For the special cases that might still need this, the instrumentation existing in python and e.g. import_file are enough.

The good things about __init__.py

Many packages use __init__.py as a way to organize their API’s to the outside world. Your package folder can have tons of scripts and only what you included in __init__.py is exposed when your folder is imported directly (eg json in the std-library). So don’t take this as an attack on __init__.py, it’s just that the import mechanism seems incomplete in my eyes. Just to be a bit specific – package maintainers don’t need to do stuff like “import os as _os” to avoid littering their module namespace when they use __init__.py as their API, that’s a nice thing to have.

Also, I’d like to hear other justifications as I’m sure more than a few exist.

The drawbacks of slashes and file-system-imports

  1. From a compatibility viewpoint, old packages aren’t affected as we’re introducing the “forward slash” in whatever future python version. Whoever uses this feature won’t be compatible with older python versions.
  2. Windows users and *nix users might argue over whether or not to allow backslashes, I think it’s not that important. Though the internet has forward slashes, so that makes it 2 platforms against 1.
  3. It’s uglier (though today’s relative imports are just as ugly and harder to learn).
  4. People might ask for absolute imports.
  5. Dividing the community and its packages into “file-system-importers” and “package-search-importers”.
  6. *reserved for complaints in the comments*

Summary

I’ve tried to do packages the existing python way and I think we can do better. The __init__.py based search mechanism works great for whatever is in sys.path, though I believe its pains outweigh its gains for organizing code. Here’s to hoping there’s a chance for relative-file-system imports in standard python.

References

http://www.python.org/dev/peps/pep-0328/

http://en.cppreference.com/w/cpp/preprocessor/include

http://effbot.org/zone/import-confusion.htm – January 07, 1999 – “There are Many Ways to Import a Module” – “The import and from-import statements are a constant cause of serious confusion for newcomers to Python”

http://stackoverflow.com/questions/448271/what-is-init-py-for

http://stackoverflow.com/questions/1260792/python-import-a-file-from-a-subdirectory 

http://docs.python.org/tutorial/modules.html

http://www.slideshare.net/stuartmitchell/python-relative-imports-just-let-me-use-the-file-system-please

The GIL Detector

Ever wonder if your flavor of python has a Global Interpreter Lock? The recipe gil_detector.py checks that.

In this day and age CPython is still core-locked; though we are seeing improvements thanks to Antoine Pitrou and other great people of the Python community. Wanting to measure just how bad the problem is – my way of looking at it was through a number I call the “python effective core count”.

Python Effective Core Count

How many cores does python see? If you bought a quad core, how many cores can each python process utilize? Measuring how long it takes to complete a given amount of work, W, then measuring how long it takes for python to run 2W using 2 threads, 3W on 3 threads, etc. The script gil_detector.py calculates:

effective_cpus = amount_of_work / (time_to_finish / baseline)

Where the baseline is the time_to_finish for 1 work unit. E.g. if it took the same amount of time to finish 4W (amount_of_work = 4) on 4 threads as it took 1W on 1 thread – python is utilizing 4 cores.

Results

I recommend reading the whole output to see the exact numbers.

Implementation Effective Core Count
Jython 2.5.2 3.8/4 cores
IronPython 2.7 3.2/4 cores
PyPy-1.5 1.0/4 cores
Stackless Python 3.2 1.0/4 cores
CPython 3.2 1.0/4 cores
CPython 2.7 0.2/4 cores

Basically, Jython has the best multithreading with IronPython not too far behind. I know multiprocessing is really easy in python, but it’s still harder. We have to solve this before 8 core CPU’s become the standard at grandma’s house. Those other languages (C/C++) utilize 3.9-4.0 cores of a quad core machine easily, why can’t we? An honorable mention goes to PyPy which by far was the fastest to execute the benchmark (10x faster). PyPy is definitely the future of Python, hopefully they can save us all. A note about CPython 2.7 – yes that number is under 1 because adding threads on python-cpu-intensive tasks hurt performance badly on older versions of the GIL, Antoine fixed that on CPython 3.2.

In my opinion the community should call this a bug and have a unittest in there yelling at us until we fix it, though it’s easy for me to complain when I’m not the core-dev. Maybe I can join PyPy and see what I can do when I find some free time. Hopefully so.

Edit – updated gil_detector.py as corrected at reddit.

A new module – import_file

So I had this python web server and I wanted to write a script that does some maintenance. The problem was, if the maintenance script isn’t part of the “__init__.py” package tree, it couldn’t use any of the web server modules. A hacky way to get around this is to add the target module’s directory to the path:

    import sys
    sys.path.append('/usr/wherever_that_module_is')
    import your_module

Another trick is using os.chdir. Even when importing modules from the same package things can become confusing as can be learned from PEP 328, PEP 366, an abundance of stackoverflow questions on the subject and many more. I’d like to quote The Zen of Python:

    Simple is better than complex.
    There should be one-- and preferably only one --obvious way to do it.
    If the implementation is hard to explain, it's a bad idea.

I don’t believe any of these can be said about python imports, at least not for anything past the trivial case of one-folder-with-all-the-modules. The moment you want to organize your project in folders it becomes complex if not complicated and unnatural.

“import math” just works and that’s great, I just wished there was an equivalent to the banal:

#include "path/to/module"

From those inferior languages. So I wrote import_file which can be used like this:

    >>>from import_file import import_file
    >>>mylib = import_file('c:\\mylib.py')
    >>>another = import_file('relative_subdir/another.py')

It’s very similar to the imp module syntax, except the function requires one argument less. This is the way it should be imo. Enjoy import_file at google code, from the cheese shop, “easy_install import_file” or pip, etc.

Pythonistas use chrome

I was very happy to see the wall of shame got so much attention. To my surprise, an extraordinary amount of visitors use the google browser as can be seen by the analytics data. Out of 24,000 visitors:

48.1% – Chrome
31.61% – Firefox
10.9% – Safari
3.95% – Mozilla compatible (what is this?)
2.35% – Internet Explorer
2.19% – Opera

Most of the visitors were unique (you guys aren’t coming back?) and it is a pretty technical, python programming related topic. So I can assume most of these are "pythonistas". Imo just like how porn decides who wins the media battles, programmers are the ones who decide who wins the browser battles. You know their grandparents/aunts/kids/uncles/etc are all going to ask them which browser to use. So expect a very bright future for google chrome.

The Python 3 Wall of Shame

Here’s my attempt at motivating package maintainers to port to python 3 and you can check out the code that generates the chart. I basically scraped PyPI (13,000 webpages) for this info and formatted it into an HTML table which is uploaded to appspot. I added a ‘cron’ task on my PC to recrawl PyPI every Sunday so the chart stays fresh. When developing the WOS I used filecache (from the previous blog post) so I could just write the code that parses the crawl as though it just now scraped PyPI while infact everything was cached to disk. Without filecache I would have had to either wait for ages, or write code that stores the scrapes, and reparses them. About 10 lines turn into an import and a decorator, now that’s magic.

I hope no one takes offense from this. The situation we’re starting at is pretty bad. Only 11 out of the top 100 packages on PyPI are labeled as supporting python3. There are a few glitches (e.g. multiprocessing) where the developers simply haven’t yet labeled the package as python 3 compliant.

Once we pass the 50% mark I guess we can change it from “Wall of Shame” to “World of Strength” or something because the subdomain is “wos”.

Filecache

Working on a project that needed some web scraping, I made filecache. I just wanted a simple decorator that would save the results of a function to disk. Memcache and other recipes seemed to be either overly complex or just plain memory caching (without persistence). If you want to help improve it then check out the google code filecache project.

Python Graphbin – A place to share graphs

A week ago I found out some strange stuff was going on when I searched for “aaaaaaaaaaa”. So I made a python script
http://pastebin.com/f35806f8f for gathering the search results and wanted to plot a nice graph. The problem was I couldn’t find a nice place to show and store the data. So I made a pastebin esque graphbin at http://graphbin.appspot.com and you can see the google search results:

http://graphbin.appspot.com/g/bedequP4

I used “Paste-It” (http://paste-it.appspot.com/) as the base for graphbin so I got a bit familiar with the “Paste”
(http://pythonpaste.org) framework. Sadly, this wasn’t a pleasant journey. A lot of the connected things are just scattered all over the place and yet seem heavily entangled (ie main.py uses
page/pasties/add.py which outputs the relevant template page in line 125 out of 342 after a flow that was no fun to follow). I’m not sure if this is a problem with “Paste” or a problem with the “Paste-It” implementation, but it got a bit ugly. Not to mention some bad naming (the “paste” folder holds the “web” framework folder and all the models, why not name the folder “models” and move the framework out? Why are pages “pasties”?).

Maybe some paste-lover can dazzle me with some info on how paste compares/differs to/from django. Drop a comment.

Python Programmers Writing Javascript Beware

Call me silly for not reading the docs, but this bug was very hard to find. Dictionaries in python are NOT the same thing in javascript. The curly braces mean it’s an "object literal" and the keys don’t need the quotation marks. For example:

var x = { NAME: 123, Something: "ok"}

Is the same as the following code:

var x = {}
x['NAME'] = 123
x['Something'] = "ok"

Which means that if you had a variable named "NAME" and you expected it’s contents to be the key, then you’re going to have a royally hard to find bug (especially when developing for an already obfuscated framework such as Google Wave).

This is even worse because JSON causes you to believe the quotation marks are needed. If there’s a place to file a JS enhancement proposal, I would, but I doubt this inconsistency would annoy anyone but a pythonista.

Projects I’d Like To Do

I’ve got too many things on my mind, I was thinking of doing the following:

  1. Help improve 3to2, sounds like it could help bridge the PyPI gap and allow for writing “backwards compatible” libraries, using the newest of technologies (it’s alot better than imitating decorator behavior using the silly syntax it’s sugar for).
  2. Help port Numpy to py3k
  3. Help port Django to py3k
  4. Build a small script that’ll crawl svn.python.org and give points to developers. [update: ohloh did it]
  5. Build a python ascii art lib (not one that does the greyscale trick, one that actually tests for lines etc).
  6. Build a pinax captcha app
  7. Make a py2exe, Freeze, py2app mashup that can easily compile on all platforms.

I think that’s it. I wonder how much of the above I’ll be able to complete by next month considering I’m really not good enough in Rock Band 2 drums yet.

Python Regular Expressions Evaluator

I wanted to try out Django over App Engine so I made an online regular expressions evaluator:

http://pythonre.appspot.com

At first I thought it’s strange that there’s no online python regular expression checker. This might not be surprising considering how easy it is to test stuff with the python interpreter as opposed to php which can be a PITA for just testing one or two lines. Either way I thought this might be useful for quick checks and as a teaching tool.