[Tutor] Importing from classes

Alan Gauld alan.gauld at btinternet.com
Wed Feb 11 10:32:02 CET 2015


On 11/02/15 02:39, daaku gee wrote:

> When importing from other modules, I've seen syntax like:
>
> import from <module> <Class>

from <module> import <name>

Note you don't import classes from modules you import names.
(The name might be the name of a class of course!)

This form is for cases where you only want to use one or two features of 
a module and don't want to have the inconvenience of typing the module 
name in front each time you use them.

> import <module>

This is the normal usage. It gives you indirect access to all of the 
module features using the <module>.<name> notation

> import from <module> <Class> as <some_name>

import <module> as <alias>
or
from <module> import <name> as <alias>

These tend to be used where the module has a very long name that
you don't want to type out in full each time, so you give it a
shorter alias.
You might also use it if you are working on code that already has
a variable with the same name as the module/feature that you want
to import. You either rename all your variable references or you
choose an alias that does not conflict.

> Is one better than the other or is it just personal choice?

'better' is often a subjective term.
There are reasons for each as described above.
What is best depends on the circumstance. If in
doubt use

import <module>

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list