Guide Python Beginner

6.13 Best Practices

Practical habits for writing memory-safe, readable Python — meaningful names, avoiding global state, using constants, and memory-efficient coding for long-running scripts.

2 min read

Meaningful Names

Choose names that describe what a variable holds (user_count, not uc) — this is the single highest-leverage readability habit, covered in 4.7 Identifiers.

Avoid Global Variables

Prefer passing values as function arguments and returning results over reading/writing global state — globals make code harder to test and reason about, since any function can silently change them (see the UnboundLocalError and global-keyword pitfalls in 6.12 Common Mistakes).

Use Constants

Replace magic numbers and strings scattered through code with named UPPER_SNAKE_CASE constants defined once — see 4.9 Constants — easier to update and self-documenting.

Memory-Efficient Coding

  • Prefer generators/iterators over building large intermediate lists when possible.
  • Delete large objects explicitly (del) once truly done with them in long-running scripts — see 6.6 Garbage Collection.
  • Reach for a shallow copy when it’s sufficient, and reserve copy.deepcopy() for nested mutable structures that genuinely need full independence — see 6.5 Copying Objects.
  • Never rely on integer caching or string interning for correctness — see 6.7 Memory Optimization.

Quick Interview Answer

“The practical habits that matter most for variables and memory: use descriptive names over abbreviations, avoid mutable global state in favor of passing arguments and returning results, replace magic values with named constants, and — for long-running or memory-sensitive scripts — prefer generators over building large lists, copy only as deep as actually needed, and explicitly del large objects once done with them.”

Common Mistakes

  • Treating these as optional style preferences rather than habits that prevent real bugs — global state and shared mutable objects are two of the most common sources of production incidents.
  • Optimizing memory prematurely in small scripts where readability matters far more than shaving a few allocations.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form