First Class Citizens in Python 3.x or earlier

According to Wikipedia, A first-class citizen in a given programming language is an entity which enables support for all the operations generally feasible to other entities.

These operations typically include being
1. Passing an argument,
2. Returning from a function,
3. Modification,
4. Assignment to a variable.

In this tutorial, we will learn about these first-class citizens present in Python 3.x or earlier. Also, we will be learning what all entities come under the tag of being First Class citizens.

First Class Citizens in Python

   Integers      Floating Point Number      Complex Numbers      Strings

Now as we are familiar with the First-Class Datatypes, let us look at first-class functions in Python 3.x or earlier.

First Class Functions in Python

First class objects are uniformly handled in Python language. Being object-oriented every entity refers to a default object which can be referenced and de-referenced at any point of time. Storage may be done using data structures or control structures.

Now we will look whether python supports first-class functions or not. So any language is said to support first-class functions when it treats functions as first-class objects.

Illustration 1 : First class function

# Python program 
# functions being be treated as objects 
def display(text): 
    return text.islower() 
  
print display('CodeSpeedy') 
  
show = display //referencing a function with the object
  
print show ('codespeedy')
Output:
False
True

Illustration 2:  First class function

# Python program 
# functions being passed as arguments to other functions 
def show(text): 
    return text.upper() 
  
def display(text): 
    return text.lower() 
  
def comb(func): 
    # storing the function in a variable 
    greeting = func("Hi, I am working on CodeSpeedy") 
    print greeting  
  
comb(display) //directly referenced by passing functions as arguments.
comb(show)    //directly referenced by passing functions as arguments.
Output:
hi, i am working on codespeedy
HI, I AM WORKING ON CODESPEEDY

Here it is clearly seen that Python functions can be referenced using an object and can also be passed as an argument to another function which clearly shows that in Python functions are First Class Citizens and can be referenced and dereferenced using an object entity.

Also, read,

Leave a Reply

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