Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static/Dynamically Scoped,Typed,Binding

Tags:

c++

python

scope

I am asking this just to clarify if i am thinking right.

Statically/Dynamically typed A language is statically typed if the type of a variable is known at compile time. This in practice means that you as the programmer must specify what type each variable is. Example: Java, C, C++.

A language is dynamically typed if the type of a variable is interpreted at runtime. This means that you as a programmer can write a little quicker because you do not have to specify type everytime. Example: Perl

Static/Dynamic Binding-which the following link clearly explains the difference Static Binding and Dynamic Binding

The main thing that i want to ask starts from here. I know the difference between Static Scoping and Dynamic Scoping. However as i was going through stack overflow people said that C++ and Python are Statically Scoped.

In c++ if i type

int void main(){
   cout<<i;          
   int i=15;
}  
int i=10;

It works(even in java).However its python equivalent

def foo():
    print(x)
    x=10
x='global'
foo()

Gives an error.

like image 272
Aditya Sharma Avatar asked Sep 26 '22 18:09

Aditya Sharma


1 Answers

The scope is static in Python as well as in C++. The difference between those languages is related to rules that define start and end of the scope of names.

In C++ the variable i is considered as global before the local definition int i=15;.

In Python: What are the rules for local and global variables in Python?:

If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Naming and binding:

When a name is used in a code block, it is resolved using the nearest enclosing scope.

So, since the variable x is assined inside foo() it is assumed to be a local variable starting from the beginning of the function foo(). It is possible to treat x within entire function block as global using the global keyword:

def foo():                
    global x              # name 'x' refers to the global variable
    print(x)              # print global 'x'
    x=10                  # assign global variable

x='global'
foo() # print 'global'
foo() # print '10'

Actually it is possible to access the global variable x even if you want to have a local name x in the same function using globals() build-it function:

def foo():                # name 'x' refers to the local variable
    print(globals()['x']) # access the global name 'x'
    x=10                  # assign local variable
    print(x)              # print local 'x'

x='global'
foo()
like image 148
Orest Hera Avatar answered Nov 15 '22 09:11

Orest Hera