[Python-3000] Changing the import machinery

Giovanni Bajo rasky at develer.com
Fri Apr 21 12:48:12 CEST 2006


Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:

>> 2) Totally disallow recursive imports (!).
>
> That would be extremely undesirable. I've used languages
> in which mutual imports weren't possible, and it's a
> massive pain in the posterior. You end up having to
> modularise things in awkward and unnatural ways to
> get around the restriction.

Point taken.

> Possibly it might work to allow mutual imports only
> of the form "import spam" and not "from spam import
> grail", but I'm not sure about that.

That would be a first step. What worries me is this fact that you access the
contents a module which is not fully imported yet. This makes us play trickes
like moving imports up and down to satisfy circular dependencies. I think that
if we prohibit the "from x import foo" syntax if x is already being imported,
people will end up doing things like:

import x    # might be circular

def func(self):
     foo = x.foo   # fake from-import, but at run-time
     [...]


Another thought. Sometimes, the order of imports does not match the order of
(import-time) dependency. It might be that user import module A, which in turns
imports module B. B then imports back module A. So the circle is user -> A ->
B -> A. Now, it might be that B depends on A's contents at import time, while A
does not depend on B's contents at import time. So, if user had imported module
B before, things would have worked out. Sometimes, 'user' is just another
module we're writing, and we've learnt to reorder our imports so we do so.

I guess there's no easy solution for this. But I had in mind something... When
you type "from spam import grail", many times you don't really need to bind
name "grail" at import-time. Sometimes you do, yes, but many times you just
want name "grail" to end up in the global dictionary of that module, but it's
not necessary that it's done *right now* when the import is processed. Python
could be note this and, if "spam" is being already imported, try to delay the
binding of name "grail" after the circular import is finished. In fact, such a
feature would really be killer because it would solve all import ordering
problems. It would leave ordering problems only if you need name at *import*
time, which is an order of magnitude less frequent.

Giovanni Bajo



More information about the Python-3000 mailing list