Special welcome gift. Get 50% off your first courses with code “AS50”. Find out more!

HomeInterviewWhat is Scope Resolution in Python?
courses 18

What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are:

  • Python modules namely ‘math’ and ‘cmath’ have a lot of functions that are common to both of them – log10()acos()exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp().
  • Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn’t change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities.
temp = 10   # global-scope variable
def func():
     temp = 20   # local-scope variable
     print(temp)
print(temp)   # output => 10
func()    # output => 20
print(temp)   # output => 10

This behavior can be overridden using the global keyword inside the function, as shown in the following example:

temp = 10   # global-scope variable
def func():
     global temp
     temp = 20   # local-scope variable
     print(temp)
print(temp)   # output => 10
func()    # output => 20
print(temp)   # output => 20

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

Categories

ads sidebar 1

You May Also Like

Oracle has several modes for shutting down the database: In normal mode, the database is shut down by default. It...
Materialized views are items that contain condensed sets of data from base tables that have been summarized, clustered, or aggregated. They...
Every database in Oracle has a tablespace called SYSTEM, which is generated automatically when the database is created. It also...