June 2019

What is Name in Python Programming?

A namespace is a system to have a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Namespaces are one honking great idea -- let's do more of those! 

Name (also called identifier) is simply a name given to objects. Everything in A python is an object. Name is a way to access the underlying object.
For example, when we do the assignment a = 2, here 2 is an object stored in memory and a is the name we associate it with. We can get the address (in RAM) of some object through the built in function, id(). Let's check it.
# Note: You may get different value of id
a = 2
# Output: id(2)= 10919424
print('id(2) =', id(2))
# Output: id(a) = 10919424
print('id(a) =', id(a))


Here, both refer to the same object. Let's make things a little more interesting.
# Note: You may get different value of id
a = 2
# Output: id(a) = 10919424
print('id(a) =', id(a))
a = a+1
# Output: id(a) = 10919456
print('id(a) =', id(a))
# Output: id(3) = 10919456
print('id(3) =', id(3))
b = 2
# Output: id(2)= 10919424
print('id(2) =', id(2))

What is happening in the above sequence of steps? A diagram will help us explain this.

Initially, an object 2 is created and the name a is associated with it, when we do a = a+1, a new object 3 is created and now associates with this object.
Note that id(a) and id(3) have the same values.
Furthermore, when we do b = 2, the new name b gets associated with the previous object 2.
This is efficient as Python doesn't have to create a new duplicate object. This dynamic nature of name binding makes Python powerful; a name could refer to any type of object.
>>> a = 5
>>> a = 'Hello World!'
>>> a = [1,2,3]

All these are valid and a will refer to three different types of object at different instances. Functions are objects too, so a name can refer to them as well.
def printHello():
    print("Hello")    
a = printHello()
# Output: Hello
a

Our same name a can refer to a function and we can call the function through it, pretty neat.


What is a Namespace in Python Programming?

So now that we understand what names are, we can move on to the concept of namespaces.
To simply put, the namespace is a collection of names.
In Python, you can imagine a namespace as a mapping of every name, you have defined, to corresponding objects.
Different namespaces can co-exist at a given time but are completely isolated.
A namespace containing all the built-in names is created when we start the Python interpreter and exists as long we don't exit.
This is the reason that built-in functions like id()print(), etc. are always available to us from any part of the program. Each module creates its own global namespace.
These different namespaces are isolated. Hence, the same name that may exist in different modules does not collide.
Modules can have various functions and classes. A local namespace is created when a function is called, which has all the names defined in it. Similar is the case with class. The following diagram may help to clarify this concept.

Python Programming Scope


Scope refers to the coding region from which a particular Python object is accessible. Hence one cannot access any particular object from anywhere from the code, the accessing has to be allowed by the scope of the object.
At any given moment, there are at least three nested scopes.
  • the innermost scope is searched first and it contains the local names
  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope
  • the next-to-last scope contains the current module's global names
  • the outermost scope, which is searched last, is the namespace containing the built-in names
When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace.
If there is a function inside another function, a new scope is nested inside the local scope.

Example of Scope and Namespace in Python

# Python program showing
# a scope of object
  
def some_func():
    print("You are welcome to some_func")
    print(var)
some_func()

Output:
You are welcome to some_funcTraceback (most recent call last):File "/home/ab866b415abb0279f2e93037ea5d6de5.py",
line 4, in some_func() File "/home/ab866b415abb0279f2e93037ea5d6de5.py",
line 3, in some_func print(var)NameError: name 'var' is not defined

As can be seen in the above output the function some_func() is in the scope from main but var is not avaialable in the scope of main. Similarly, in the case of inner functions, outer functions don’t have the accessibility of inner local variables which are local to inner functions and out of scope for outer functions. 
In the next example, we’ll see the list of names inside some nested functions. The code in this block continues from the previous block.

def outer_foo():
    outer_var = 3
    def inner_foo():
        inner_var = 5
        print(dir(), ' - names in inner_foo')
    outer_var = 7
    inner_foo()
    print(dir(), ' - names in outer_foo')
     
outer_foo()
The output is as follows.

['inner_var']  - names in inner_foo
['inner_foo', 'outer_var']  - names in outer_foo
The above example defines two variables and a function inside the scope of outer_foo(). Inside the inner_foo(), the dir() function only displays one name i.e. “inner_var”. It is alright as the “inner_var” is the only variable defined in there.

Python Programming Type Casting/Conversion:

The process of converting the value of one data type such as integer, string, float, etc. to another data type is called type conversion/ typecasting. Python has two types of type conversion/typecasting.
  1. Implicit Type Conversion
  2. Explicit Type Casting

Implicit Type Conversion:

In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.
Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.


Example 
Converting integer to float
n_int = 234
n_flo = 2.34
n_new = n_int + n_flo
print("datatype of n_int:",type(n_int))
print("datatype of num_flo:",type(n_flo))
print("Value of n_new:",n_new)
print("datatype of n_new:",type(n_new))

When we run the above program, the output will be
datatype of n_int:
datatype of n_flo:
Value of n_new: 234.25
datatype of n_new:
In the above program,
  • We add two variables n_int and n_flo, storing the value in n_new.
  • We will look at the data type of all three objects respectively.
  • In the output, we can see the datatype of n_int is an integer, the datatype of n_flo is float.
  • Also, we can see the n_new has float data type because Python always converts smaller data type to larger data type to avoid the loss of data.
Now, let us try adding a string and an integer, and see how Python treats it.

Explicit Type Casting:

In Explicit Type Conversion, users convert the data type of an object to required datatype. We use the predefined functions like int()float()str(), etc to perform explicit type conversion.
This type conversion is also called typecasting because of the user casts (change) the data type of the objects.
Syntax :
(required_datatype)(expression)
Typecasting can be done by assigning the required data type function to the expression.

Example
Addition of string and integer using explicit casting
n_int = 123
n_str = "456"
print("Data type of n_int:",type(n_int))
print("Data type of n_str before Type Casting:",type(n_str))
num_str = int(n_str)
print("Data type of n_str after Type Casting:",type(n_str))
num_sum = n_int + n_str
print("Sum of n_int and n_str:",n_sum)
print("Data type of the sum:",type(n_sum))
When we run the above program, the output will be
Data type of n_int:
Data type of n_str before Type Casting:
Data type of n_str after Type Casting:
Sum of n_int and n_str: 579
Data type of the sum:
In above program,
  • We add n_str and n_int variable.
  • We converted n_str from string(higher) to integer(lower) type using int() function to perform the addition.
  • After converting n_str to an integer value Python is able to add these two variable.
  • We got the n_sum value and data type to be an integer.

Key Points to Remember:
  1. Type Casting is the conversion of an object from one data type to another data type.
  2. Implicit Type Casting is automatically performed by the Python interpreter.
  3. Python avoids the loss of data in Implicit Type Conversion.
  4. Explicit Type Casting the data types of object are converted using predefined function by the user.
  5. In Type Casting loss of data may occur as we enforce the object to the specific data type.

Examples:-


def validSalary(sal):                                                           
try:
sal = float(sal);
return 4000 <= sal <= 7000;
except ValueError as ex:
return False;

print "Salary '5000' is ", validSalary('5000');
print "Salary '5000.0' is ", validSalary('5000.0');
print "Salary '' is ", validSalary('');

Output:

$ python type_conversion.py
Salary '5000' is True
Salary '5000.0' is True
Salary '' is False

Frozen set

The frozen set is just an immutable version of a Python set object. Elements of a frozen set cannot be modified at any time, remains the same after creation but elements in set can be modified.
Returns an empty frozenset if no parameters in frozenset method.
#!/usr/bin/python                                                               

var_b = {1, 2, 3, 6, 7};

var_result = frozenset(var_b);
print("frozenset is: %s" % var_result);

print("frozenset empty is: %s" % frozenset());
Output:
$ python typte_conversion.py
frozenset is: frozenset([1, 2, 3, 6, 7])
frozenset empty is: frozenset([])