2

I'm running through the Django tutorial.

After editing a class it says:

Save these changes and start a new Python interactive shell by running python manage.py shell again:

>>> from polls.models import Poll, Choice

Is it possible to do that without quitting the shell?

DD.
  • 21,498
  • 52
  • 157
  • 246

4 Answers4

2

No, it's not. Every edit you make to .py files will NOT get reloaded in the shell automatically. If you want to have that type of feature you would have to use

django-extensions which supports what you're after.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
1

Not sure I agree with the other answer.

Python has a built in function reload() which, from the docs:

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before.

This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

However you have to do from polls import models and then models.Poll (as it has to be passed the actual module rather than a class) and models.Choice in your code.

That way, without leaving the shell you can run reload(models).

Edit 1:

If you can't be bothered typing models. all the time, you can also enter in your own shortcut;

from polls import models as pm
pm.Poll
pm.Choice

reload(pm)
Community
  • 1
  • 1
Ewan
  • 14,592
  • 6
  • 48
  • 62
0

I have encountered this situation sometimes. And it's already discussed on SO.

It's true, reload() works. But at the same time it's not a very convenient option.

>>> from polls.models import Poll, Choice
.... #Some changes are done to your polls/models.py file and saved

>>> Poll #gives you old model
>>> reload(polls.models) #Reload works at module level!
>>> from polls.models import Poll, Choice # import again from the reloaded module
>>> Poll #gives you new model
Community
  • 1
  • 1
Sudipta
  • 4,773
  • 2
  • 27
  • 42
0

What about?

def reload_all():
    import sys
    module = type(sys) # this type has no name!
    for m in sys.modules.values():
        if isinstance(m, module):
            try:
                reload(m)
            except:
                pass

Not sure if this may have any side effect, though.

rodrigo
  • 94,151
  • 12
  • 143
  • 190