Dodging Wildcard Variable Shadowing
Intuitive Python — by David Muller (39 / 41)
👈 Keeping Your Source Organized | TOC | Wrapping Up 👉
Few things are more destructive for a code base then a programmer operating under flawed assumptions. We want to write code that makes it clear to others what calling a piece of code does and what effects it might have.
In an earlier chapter, you learned how to use flake8 to catch certain types of errors before you even run your Python code. One of the dangerous classes of errors that flake8 helps you avoid is variable shadowing from * (“wildcard”) imports.
Consider the following toy file that provides two methods for managing dinosaurs:
from veterinarian import *
from lab import *
def euthanize_dinosaurs():
for dinosaur in get_dinosaurs():
print(f"Euthanizing {dinosaur}")
def run_experiments():
for dinosaur in get_dinosaurs():
print(f"Running experiment on {dinosaur}")
The euthanize_dinosaurs function euthanizes all dinosaurs returned by get_dinosaurs. The run_experiments function runs an experiment on all dinosaurs returned by get_dinosaurs. But, where is get_dinosaurs defined? Is it defined in veterinarian or in lab? Is it defined in both?
For the sake of example, let’s say both veterinarian and lab defined a get_dinosaurs function. Which…