Python interpreter tricks


John Anderson has documented some nice Python interpreter tricks on his blog. Including a .pythonrc.py file hack for Djangonauts:

For Django developers when you load up the ./manage.py shell it is nice to have access to all your models and settings for testing:

# If we're working with a Django project, set up the environment
if 'DJANGO_SETTINGS_MODULE' in os.environ:
    from django.db.models.loading import get_models
    from django.test.client import Client
    from django.test.utils import setup_test_environment, teardown_test_environment
    from django.conf import settings as S

    class DjangoModels(object):
        """Loop through all the models in INSTALLED_APPS and import them."""
        def __init__(self):
            for m in get_models():
                setattr(self, m.__name__, m)

    A = DjangoModels()
    C = Client()

See his post for more interesting Python tips. Me, I’m enabling autocomplete and automatic pretty-printing right now.

5 comments
  1. Greg Turner said:

    Nice tip, but your snow effect had me momentarily scared that my vision was degrading, as parts of letters kept disappearing!

  2. ksamuel said:

    What about just installing django_extensions and just use ./manage.py shell_plus? It does the same and even more, minus hacking and a lot of code lines.

  3. Miguel said:

    For this I use django-extensions.

    You can do:

    ./manage.py shell_plus (--print-sql)

    Good hint, though, thanks.

  4. John said:

    @ksmauel @Miguel: I haven’t tried django_extensions before, out of inertia I guess. It looks very juicy. Thanks for the tip!

  5. I use django_extensions with shell_plus for some projects but this is a universal way to get the same functionality, no longer needing to include a separate app into your project (or when working on open source projects that don’t have it already included).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: