Knowledgebase

Understanding Scope Print

  • python, guide, howto, solution, zillionkinghost, hosting, support
  • 0

Where names are visible.

WHAT SCOPE MEANS

Which parts of your code can see a given name.

THE BASIC RULE

A name assigned inside a function exists only inside it.

A name assigned at the top level is visible throughout the file.

WHY THAT MATTERS

It prevents functions interfering with each other.

WHAT SURPRISES PEOPLE

A function can read a name from the enclosing scope but cannot reassign it without declaring that intention.

WHAT TO DO

Pass values in as arguments and return results.

Rather than relying on names defined elsewhere.

WHY

Functions depending on external state are hard to test and hard to reason about.

GLOBAL VALUES

Possible, and usually a sign the design could be better.

WHAT TO USE INSTEAD

Arguments and return values Configuration passed explicitly

WHAT TO BE CAREFUL WITH

Reusing a name inside a function that also exists outside it Assuming a change inside a function affects the outside

WHAT DOES CARRY OUT

Changes to mutable objects passed in, such as lists and dictionaries.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot