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 thoughts on “Python interpreter tricks

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

  2. 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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.