Practice: Installing External Packages

« Read the chapter

Q1. Is a module available

BeginnerCoding

Write a function has_module(name) that returns True when importlib.util.find_spec finds the module. Print the result for 'math' and 'zzz_missing_pkg'.

Goal: Check for packages

Q2. Catch a missing import

BeginnerCoding

Try to import the module nothing_here_xyz. If it is missing, print 'install it first'.

Goal: Handle ImportError

Q3. Parse pinned lines

BeginnerCoding

For the lines ['a==1.0', 'b==2.5'] print each as 'name:version' using split.

Goal: Read requirements

Q4. Skip comments

IntermediateCoding

Given the lines ['# tools', 'requests', '', 'flask'], print only the real requirements.

Goal: Read requirements

Q5. Build an install command

IntermediateCoding

Write a function install_cmd(name, version=None) returning the pip command text. With a version it should use ==. Print the results for ('requests', None) and ('flask', '3.0.0').

Goal: Pin a version

Q6. Major version

IntermediateCoding

Write major(v) that returns the first number of a version text as an int. Print major('2.31.4') and major('10.0').

Goal: Understand versions

Q7. Version tuple compare

AdvancedCoding

Convert '1.10.0' and '1.9.0' to tuples of ints and print which one is newer. Why is a plain text comparison risky?

Goal: Understand versions

Q8. Count requirements

IntermediateApplication

A requirements text has some lines. Count how many are real requirements (not blank, not comments).

Goal: Read requirements

Q9. Fallback pattern

IntermediateApplication

Write code that tries import tomllib_fake_xyz and sets mode to 'fast' on success or 'plain' when the module is missing. Print mode.

Goal: Handle ImportError

Q10. Version of a missing package

AdvancedCoding

Use importlib.metadata.version for 'zz-no-such-dist'. Print 'missing' if PackageNotFoundError is raised.

Goal: Check installed versions

Q11. Split a range

BeginnerOutput

What does this print?

Code
spec = 'flask>=2.0'
name, low = spec.split('>=')
print(name)
print(low)

Goal: Read requirements

Q12. Startswith check

BeginnerOutput

What does this print?

Code
for line in ['# note', 'numpy', '']:
    print(line.startswith('#'))

Goal: Read requirements

Q13. Specifier list

IntermediateOutput

What does this print?

Code
specs = ['a==1', 'b>=2', 'c==3']
pinned = [s for s in specs if '==' in s]
print(pinned)
print(len(pinned))

Goal: Pin a version

Q14. Find spec result

IntermediateOutput

What does this print?

Code
import importlib.util
print(importlib.util.find_spec('os') is None)
print(importlib.util.find_spec('no_pkg_here_q') is None)

Goal: Check for packages

Q15. Exception class

IntermediateOutput

What does this print?

Code
print(issubclass(ModuleNotFoundError, ImportError))
try:
    import no_pkg_here_q
except ImportError as e:
    print(type(e).__name__)

Goal: Handle ImportError

Q16. Tuple versions

AdvancedOutput

What does this print?

Code
v = '3.11.2'
parts = tuple(int(p) for p in v.split('.'))
print(parts)
print(parts >= (3, 10))

Goal: Understand versions

Q17. Fix the install name

BeginnerDebugging

This program fails because the import name is wrong. Fix it so it prints the module name 'bs4' as text without importing anything.

Code
import beautifulsoup4
print('bs4')

Goal: Know names

Q18. Fix the except

IntermediateDebugging

The program should print 'missing' but the except clause is wrong. Fix it.

Code
try:
    import no_pkg_here_q
except ValueError:
    print('missing')

Goal: Handle ImportError

Q19. Fix the split

IntermediateDebugging

The code should print the version 1.4, but it crashes. Fix it.

Code
line = 'pkg==1.4'
name, version = line.split('=')
print(version)

Goal: Read requirements

Q20. pip vs PyPI

BeginnerConceptual

Explain the difference between pip and PyPI in one or two sentences.

Goal: Know the tools