[Dev] Upcoming Chandler date/time related changes

Phillip J. Eby pje at telecommunity.com
Tue May 24 15:53:02 PDT 2005


At 03:16 PM 5/24/2005 -0700, Heikki Toivonen wrote:
>Phillip J. Eby wrote:
> > At 02:07 PM 5/24/2005 -0700, Heikki Toivonen wrote:
> >
> >> > +from datetime import datetime
> >>
> >> This is just a general note about from vs import. I think we determined
> >> that import is better, so things like this would be better to write:
> >>
> >> import datetime.datetime as datetime
> >
> > Since these two statements do the same thing, I don't understand how/why
> > one could be better, unless you mean readability.  However, from a
>
>I think there are subtle differences. I would have to check, but I
>believe one difference is that with import doing reload() would work as
>expected, but not so with from. In other words, doing:
>
>from datetime import datetime
># then sometime later call
>reload(datetime)
>
>would be slightly different than:
>
>import datetime.datetime as datetime
># then sometime later call
>reload(datetime)

Actually, both of these will fail, because the 'datetime' being imported is 
not a module, e.g.:

     >>> from datetime import datetime
     >>> reload(datetime)

     Traceback (most recent call last):
       File "<pyshell#1>", line 1, in -toplevel-
         reload(datetime)
     TypeError: reload() argument must be module

     >>> datetime
     <type 'datetime.datetime'>

Now, have a look at this:

     >>> import datetime.datetime as datetime

     Traceback (most recent call last):
       File "<pyshell#0>", line 1, in -toplevel-
         import datetime.datetime as datetime
     ImportError: No module named datetime

In other words, your proposed version doesn't actually work at all, which 
surprised me because I didn't realize that "import x.y as z" requires that 
"x.y" be a module.

So, the two forms are not semantically equivalent unless the item being 
imported is a module; in all other cases you must use the "from" form if 
you wish to have the name added to your module's namespace.


>We haven't been rigorous with enforcing the convention though. And I
>don't know if we are actually using reload(), or if we are even planning
>on using it, or if it would actually be a bad idea to even try use it.

In this particular case, reload() won't work with either form, because the 
desired object (the 'datetime' type) is not a module.

However, assuming that the object you are importing *is* a module, then it 
doesn't matter how you import it; reload() just expects a module object.



More information about the Dev mailing list