Import styles: import, from and as
`import json` keeps a module's names behind its name, `from collections import Counter` brings one name in directly, and `as` renames. Each choice decides which names your code has, and which ones can collide.
- Explain what
import x,from x import yandimport x as zeach bind in your program - Recognise ImportError for a name the module doesn't have
- Spot and fix a clash where a later import or definition replaces an earlier name
Since the Collections & Itertools module you've written from collections import Counter. An import does two things: it finds the module and runs it (once per program), then it binds a name in your file. The style decides which name:
import jsonbindsjson, the module itself. You writejson.dumps(...), so every call says where it comes from.from collections import Counterbinds justCounter. Shorter, but a reader has to look at the top of the file to know where it's from.import statistics as statsbinds the module under another name. Use it for long names or well-known conventions (you'll meetimport pandas as pdlater), and to avoid clashes.
Run each example to see what it prints. Running examples doesn't count toward progress.
import json from collections import Counter import statistics as stats ratings = [5, 4, 5, 3, 5] print(json.dumps({"ratings": ratings})) print(Counter(ratings).most_common(1)) print(stats.median(ratings))
A name can only mean one thing at a time. from x import y and def y(...) both bind y, so the later one silently replaces the earlier. The classic case: the time module (for time.sleep) and the time type from datetime (a clock time like 09:30).
import time from datetime import time opening = time(9, 30) time.sleep(0.1)
import time from datetime import time as clock_time opening = clock_time(9, 30) closing = clock_time(17, 0) print(opening, closing, opening < closing) pause = 0.01 time.sleep(pause) print("slept for", pause, "seconds")
When to use which: import module when you use several of its names or the module name helps the reader (json.loads, csv.DictReader); from module import name for one or two names used often (Counter, Decimal); as for conventions and clashes. Put imports at the top of the file. Mistakes to avoid: importing two things with the same name, naming your own variable or function after something you imported, and from module import *, which dumps every name in and makes clashes invisible.
import mbinds the module (m.name),from m import namebinds one name,asrenames.- A name the module doesn't have raises ImportError; a later import or
defwith the same name replaces the earlier one. - Use the module name or
aswhen two modules share a name. - Next: your own file as a module.