Python - Trouble Shooting

error: externally-managed-environment (PEP 668)

In modern Linux distributions (Debian 12+, Ubuntu 23.04+), running pip install globally is blocked to prevent breaking system-level apt packages.

Problem

error: externally-managed-environment
× This environment is externally managed
╰─> To install Python packages system-wide, try apt install

Solution

Create and activate a local virtual environment:

python3 -m venv .venv
source .venv/bin/activate
pip install <package-name>

Alternatively, for standalone CLI tools, use pipx:

pipx install <package-name>

fatal error: Python.h: No such file or directory

Occurs when compiling C/C++ extensions or building native wheels without Python C headers installed.

Solution

Install Python 3 header development packages:

# Ubuntu / Debian
sudo apt update && sudo apt install -y python3-dev build-essential

# Fedora / RHEL
sudo dnf install -y python3-devel gcc

# macOS (Homebrew)
brew install python

ModuleNotFoundError: No module named 'xxx'

Problem

Python cannot find the imported package in the current environment's sys.path.

Solution

  1. Verify whether you are inside the active virtual environment:
    which python3
    which pip
    
  2. Verify package installation:
    pip list | grep <package-name>
    
  3. For local packages or relative imports, set PYTHONPATH:
    export PYTHONPATH="${PYTHONPATH}:."
    

TypeError: 'xxx' object is not callable

Problem

Accidentally using function call syntax () on an object that is not a function, such as a dictionary, list, module, or shadowed built-in:

data = {"a": 1}
val = data("a")  # TypeError: 'dict' object is not callable

Solution

Use bracket indexing data["a"] instead of parentheses data("a"). Ensure you did not name a variable after a module or built-in (e.g., list = [1, 2]).

RuntimeError: dictionary changed size during iteration

Problem

Modifying a dictionary's keys while iterating directly over it:

d = {"a": 1, "b": 2, "c": 3}
for k in d:
    if d[k] % 2 == 0:
        del d[k]  # RuntimeError!

Solution

Iterate over a static copy of keys:

for k in list(d.keys()):
    if d[k] % 2 == 0:
        del d[k]

UnboundLocalError: local variable referenced before assignment

Problem

Assigning to a variable inside an inner function causes Python to treat it as a local variable across the entire function scope, breaking reads before the assignment:

count = 0
def increment():
    print(count)  # UnboundLocalError!
    count += 1

Solution

Declare the variable as global (module scope) or nonlocal (enclosing function scope):

def increment():
    global count
    print(count)
    count += 1

NameError: name 'reduce' is not defined

In Python 3, reduce is no longer a built-in function. Import it from functools:

from functools import reduce