Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com

function

15 min read

 

globals() function


globals() function in Python returns the dictionary of current global symbol table.

Symbol table: Symbol table is a data structure which contains all necessary information about the program. These include variable names, methods, classes, etc.
Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() method.

The functions, variables which are not associated with any class or function are stored in global scope.

Syntax: globals()

Parameters: No parameters required.
# Python3 program to demonstrate global() function
  
# global variable
a = 5
  
def func():
    c = 10
    d = c + a
      
    # Calling globals()
    globals()['a'] = d
    print (d)
      
# Driver Code    
func()

Output:

15

hasattr() Function

The python hasattr() function returns true if an object has given named attribute. Otherwise, it returns false.

Signature

  1. hasattr(object, attribute)  

Parameters

object: It is an object whose named attribute is to be checked.

attribute: It is the name of the attribute that you want to search.

Return

It returns true if an object has given named attribute. Otherwise, it returns false.

Python hasattr() Function Example 1

The below example shows the working of hasattr().

  1. class Employee:  
  2.     age = 21  
  3.     name = 'Phill'  
  4.   
  5. employee = Employee()  
  6.   
  7. print('Employee has age?:', hasattr(employee, 'age'))  
  8. print('Employee has salary?:', hasattr(employee, 'salary'))  

Output:

Employee has age?: True
Employee has salary?: False


locals() function

Python locals() function returns the dictionary of the current local symbol table.

  • Symbol table: It is a data structure created by a compiler for which is used to store all information needed to execute a program.
  • Local symbol Table: This symbol table stores all information needed for the local scope of the program and this information is accessed using python built-in function locals().

Syntax : locals()

Parameters: This function does not takes any input parameter. 

Return Type : This returns the information stored in local symbol table.

Python locals() works insides a local scope

# Python program to understand about locals
# here no local variable is present
 
def demo1():
    print("Here no local variable  is present : ", locals())
 
# here local variables are present
def demo2():
    name = "Ankit"
    print("Here local variables are present : ", locals())
 
# driver code
demo1()
demo2()

Output;

Here no local variable  is present :  {}

Here local variables are present : {'name': 'Ankit'}

map() function

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Syntax :

map(fun, iter)

Parameters :

fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.

NOTE : You can pass one or more iterable to the map() function.

Returns :

Returns a list of the results after applying the given function  
to each item of a given iterable (list, tuple etc.) 
# Python program to demonstrate working
# of map.
  
# Return double of n
def addition(n):
    return n + n
  
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))

Output :

[2, 4, 6, 8]

Memory view

memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying. The memoryview() function allows direct read and write access to an object’s byte-oriented data without needing to copy it first. That can yield large performance gains when operating on large objects since it doesn’t create a copy when slicing.

Syntax: memoryview(obj)

Parameters:

  • obj – object whose internal data is to be exposed.
  • supporting buffer protocol – str and bytearray (but not unicode).

Return Value: Returns a memoryview object.

Python memoryview() Example

Example 1: Python memoryview() works

byte_array = bytearray('XYZ', 'utf-8')
 
mv = memoryview(byte_array)
 
print(mv[0])
print(bytes(mv[0:1]))

Output:

88
b'X

object() function

object() function returns the empty object, and the Python object takes no parameters.

Syntax of Python object()

For versions of Python 3.x, the default situation. The base class for all classes, including user-defined ones, is the Python object class. As a result, in Python, all classes inherit from the Object class.

Syntax : obj = object()

Parameters :  None

Example of Python object() 

In this case, the object() function was used to create a new object, and the type() and dir() methods were used to identify the object’s characteristics. We can see from the results that obj is a part of the object class. We can also observe that there is no __dict__ attribute on obj. As a result, we are unable to give an instance of the object class attributes.

# declaring the object of class object
obj = object()
 
# printing its type
print("The type of object class object is: ")
print(type(obj))
 
# printing its attributes
print("The attributes of its class are: ")
print(dir(obj))

Output: 

The type of object class object is : 
The attributes of its class are : 

[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]

open() Function

The python open() function opens the file and returns a corresponding file object.

Signature

  1. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)  

Parameters

file: It is a path like object giving the pathname of the file to be opened.

mode (optional): It specifies the mode in which the file is opened. If not provided, it defaults to 'r' which means open for reading in text mode.

buffering (optional): It is used to set buffering policy.

encoding (optional): It is a name of the encoding to encode or decode the file.

errors (optional): A string that specify how to handle encoding/decoding errors.

newline (optional): It controls how newlines mode works (available values: None, ' ', '\n', 'r', and '\r\n'

closefd (optional): It must be True (default) if given otherwise an exception will be raised.

opener (optional): a custom opener; must return an open file descriptor.

Return

It returns a file object which can used to read, write and modify file.

Python open() Function Example 1

The below example shows how to open a file in Python.

  1. # opens python.text file of the current directory  
  2. f = open("python.txt")  
  3. # specifying full path  
  4. f = open("C:/Python33/README.txt")  

Output:

Since the mode is omitted, the file is opened in 'r' mode; opens for reading.

delattr() Function

Python delattr() function is used to delete an attribute from a class. It takes two parameters first is an object of the class and second is an attribute which we want to delete. After deleting the attribute, it no longer available in the class and throws an error if try to call it using the class object.

Signature

  1. delattr (object, name)  

Parameters

object: Object of the class which contains the attribute.

name: The name of the attribute to delete. It must be a string.

Return

It returns a complex number.

Example 1

It is a simple example which contains a Student class, and by using delattr() function, we will delete it's email attribute.

  1. # Python delattr() function example  
  2. class Student:  
  3.     id = 101  
  4.     name = "Rohan"  
  5.     email = "rohan@abc.com"  
  6.     def getinfo(self):  
  7.         print(self.id, self.name, self.email)  
  8. s = Student()  
  9. s.getinfo()  
  10. delattr(Student,'email'# Removing attribute  
  11. s.getinfo() # error: no attribute 'email' is available  

Output:

AttributeError: 'Student' object has no attribute 'email'
101 Rohan rohan@abc.com

 

setattr() Function

Python setattr() function is used to set a value to the object's attribute. It takes three arguments an object, a string, and an arbitrary value, and returns none. It is helpful when we want to add a new attribute to an object and set a value to it. The signature of the function is given below.

Signature

  1. setattr (object, name, value)  

Parameters

object: It is an object which allows its attributes to be changed.

name : A name of the attribute.

value : A value, set to the attribute.

Example 1

Here, we are adding a new attribute and setting its value by using the setattr() function.

  1. class Student:  
  2.     id = 0  
  3.     name = ""  
  4.       
  5.     def __init__(self, id, name):  
  6.         self.id = id  
  7.         self.name = name  
  8.           
  9. student = Student(102,"Sohan")  
  10. print(student.id)  
  11. print(student.name)  
  12. #print(student.email) product error  
  13. setattr(student, 'email','sohan@abc.com'# adding new attribute  
  14. print(student.email)  

Output:

102
Sohan
sohan@abc.com


isinstance() function

 isinstance() function returns True if the object is specified types, and it will not match then return False. 

Syntax: 

isinstance(obj, class)

Parameters : 

  • obj : The object that need to be checked as a part of class or not.
  • class : class/type/tuple of class or type, against which object is needed to be checked.

Returns : True, if object belongs to the given class/type if single class is passed or any of the class/type if tuple of class/type is passed, else returns False. Raises 

Python isinstance with int and list

# Python 3 code to demonstrate
# working of isinstance()
# with native types
 
# initializing native types
test_int = 5
test_list = [1, 2, 3]
 
# testing with isinstance
print("Is test_int integer? : " + str(isinstance(test_int, int)))
print("Is test_int string? : " + str(isinstance(test_int, str)))
print("Is test_list integer? : " + str(isinstance(test_list, int)))
print("Is test_list list? : " + str(isinstance(test_list, list)))
 
# testing with tuple
print("Is test_int integer or list or string? : "
      + str(isinstance(test_int, (int, list, str))))

Output: 

Is test_int integer? : True
Is test_int string? : False
Is test_list integer? : False
Is test_list list? : True
Is test_int integer or list or string? : True

issubclass() function

issubclass() in Python

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False.

Syntax: issubclass( object, classinfo ) 

Parameters: 

  • Object: class to be checked
  • classinfo: class, types or a tuple of classes and types 

Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

Example 1:

For issubclass python we are defining multiple classes and representing the phenomenon of Inheritance, then for a particular class we are checking whether it is the subclass for the mentioned base class or not.

Python3

# Python program to demonstrate
# issubclass()
 
 
# Defining Parent class
class Vehicles:
 
    # Constructor
    def __init__(vehicleType):
        print('Vehicles is a ', vehicleType)
 
# Defining Child class
class Car(Vehicles):
 
    # Constructor
    def __init__(self):
        Vehicles.__init__('Car')
 
# Driver's code  
print(issubclass(Car, Vehicles))
print(issubclass(Car, list))
print(issubclass(Car, Car))
print(issubclass(Car, (list, Vehicles)))

Output: 

True
False
True

True

vars() function

 This is an inbuilt function in Python. The vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be can a module, a class, an instance, or any object having __dict__ attribute. 

Syntax: 
 

vars(object)

The method returns the __dict__ attribute for a module, class, instance, or any other object if the same has a __dict__ attribute. If the object fails to match the attribute, it raises a TypeError exception. Objects such as modules and instances have an updatable __dict__ attribute however, other objects may have written restrictions on their __dict__ attributes. vars() acts like locals() method when an empty argument is passed which implies that the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. 
 

# Python program to illustrate
# working of vars() method in Python
 
class Geeks:
  def __init__(self, name1 = "Arun", num2 = 46, name3 = "Rishab"):
    self.name1 = name1
    self.num2 = num2
    self.name3 = name3
   
GeeksforGeeks = Geeks()
print(vars(GeeksforGeeks))

Output: 
 

{'num2': 46, 'name1': 'Arun', 'name3': 'Rishab'}

zip()

Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. 

It is used to map the similar index of multiple containers so that they can be used just using a single entity. 

Syntax :  zip(*iterators) 

Parameters : Python iterables or containers ( list, string etc ) 
Return Value : Returns a single iterator object, having mapped values from all the 
containers.

example

Example 1: Python zip two lists

name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
 
# using zip() to map values
mapped = zip(name, roll_no)
 
print(set(mapped))

Output:

{('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)} 


 

bytes() method

Python byte() function converts an object to an immutable byte-represented object of given size and data.

Syntax : bytes(src, enc, err)

Parameters : 

  • src : The source object which has to be converted
  • enc : The encoding required in case object is a string
  • err : Way to handle error in case the string conversion fails.

Returns :  Byte immutable object consisting of unicode 0-256 characters according to src type. 

# python code demonstrating
# int to bytes
str = "Welcome "
 
arr = bytes(str, 'utf-8')
 
print(arr)

Output:

b'Welcome ' 

callable()

callable is something that can be called. This built-in method in Python checks and returns True if the object passed appears to be callable, but may not be, otherwise False.
Syntax:

callable(object)

The callable() method takes only one argument, an object and returns one of the two values:

  • returns True, if the object appears to be callable.
  • returns False, if the object is not callable.
# Python program to illustrate 
# callable()
# a test function
def Geek():
    return 5
  
# an object is created of Geek()
let = Geek
print(callable(let))
  
# a test variable
num = 5 * 5
print(callable(num))

Output:

True
False

compile() Function

The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.

Signature

compile(source, filename, mode, flag, dont_inherit, optimize)

Parameters

  • source - normal string, a byte string, or an AST (Abstract Syntax Trees) object.
  • filename - File from which the code is read.
  • mode - mode can be either exec or eval or single.
    • eval - if the source is a single expression.
    • exec - if the source is block of statements.
    • single - if the source is single statement.
  • flags and dont_inherit - Default Value= 0. Both are optional parameters. It monitors that which future statements affect the compilation of the source.
  • optimize (optional) - Default value -1. It defines the optimization level of the compiler.
  1. # compile string source to code  
  2. code_str = 'x=5\ny=10\nprint("sum =",x+y)'  
  3. code = compile(code_str, 'sum.py''exec')  
  4. print(type(code))  
  5. exec(code)  
  6. exec(x)  

Output:

<class 'code'>
sum = 15

 

bytearray() function

bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.

Syntax:

bytearray(source, encoding, errors)

Parameters:

source[optional]: Initializes the array of bytes
encoding[optional]: Encoding of the string
errors[optional]: Takes action when encoding fails
str = "Geeksforgeeks"
  
# encoding the string with unicode 8 and 16
array1 = bytearray(str, 'utf-8')
array2 = bytearray(str, 'utf-16')
  
print(array1)
print(array2)

Output:

bytearray(b'Geeksforgeeks')
bytearray(b'\xff\xfeG\x00e\x00e\x00k\x00s\x00f\x00o\x00r\x00g\x00e\x00e\x00k\x00s\x00')

frozenset() Function

The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.

Signature

  1. frozenset(iterable)  

Parameters

iterable: An iterable object such as list, tuple etc.

Return

It returns an immutable frozenset object initialized with elements from the given iterable.

Python frozenset() Function Example 1

  1. # tuple of letters  
  2. letters = ('m''r''o''t''s')  
  3.   
  4. fSet = frozenset(letters)  
  5. print('Frozen set is:', fSet)  
  6. print('Empty frozen set is:', frozenset())  

Output:

Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})

Empty frozen set is: frozenset() 

 

 

hash() Function

Python has() function is used to get the hash value of an object. Python calculates the hash value by using the hash algorithm. The hash values are integers an used to compare dictionary keys during a dictionary lookup. We can hash only these types:

Hashable types: * bool * int * long * float * string * Unicode * tuple * code object

We cannot hash of these types:

Non-hashable types: * bytearray * list * set * dictionary * memoryview

 hash() Function Example 1

Here, we are getting hash values of integer and float values. See the below example.

  1. # Python hash() function example  
  2. # Calling function  
  3. result = hash(21# integer value  
  4. result2 = hash(22.2# decimal value  
  5. # Displaying result  
  6. print(result)  
  7. print(result2)  

Output:

21


ascii()

ascii() Function Syntax

Syntax: ascii(object)

  • object: Any Python object (ex.: string, int, list, tuple, set, etc.)

Returns: Returns a string as a printable representation of the object passed, escaping the non-ASCII characters.

The method can take only one parameter, an object that can be a list, strings, etc. As already discussed, it returns a printable representation of an object.

ascii("¥")

Output:

\xa5

Tuple

A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

__call__ in Python

 __call__ is one of them. The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

object() is shorthand for object.__call__()

Example 1:

class Example:
    def __init__(self):
        print("Instance Created")
      
    # Defining __call__ method
    def __call__(self):
        print("Instance is called via special method")
  
# Instance created
e = Example()
  
# __call__ method will be called
e()

Output :

Instance Created
Instance is called via special method

divmod()

divmod() method in python takes two numbers and returns a pair of numbers consisting of their quotient and remainder. 

Syntax : 

divmod(x, y)
x and y : x is numerator and y is denominator
x and y must be non complex

Examples:  

Input : x = 9, y = 3
Output :(3, 0)

Input : x = 8, y = 3
Output :(2, 2)

Explanation: The divmod() method takes two parameters x and y, where x is treated as numerator and y is treated as the denominator. The method calculates both x // y and x % y and returns both the values. 

# Python3 code to illustrate divmod()
# divmod() with int
print('(5, 4) = ', divmod(5, 4))
print('(10, 16) = ', divmod(10, 16))
print('(11, 11) = ', divmod(11, 11))
print('(15, 13) = ', divmod(15, 13))
 
# divmod() with int and Floats
print('(8.0, 3) = ', divmod(8.0, 3))
print('(3, 8.0) = ', divmod(3, 8.0))
print('(7.5, 2.5) = ', divmod(7.5, 2.5))
print('(2.6, 10.7) = ', divmod(2.6, 0.5))

Output: 

(5, 4) =  (1, 1)
(10, 16) =  (0, 10)
(11, 11) =  (1, 0)
(15, 13) =  (1, 2)
(6.0, 5) =  (2.0, 2.0)
(3, 9.0) =  (0.0, 3.0)
(13.5, 6.2) =  (3.0, 0.0
(1.6, 10.7) =  (5.0, 0.10000000000000009)

Help function in Python

Python help function is used to display the documentation of modules, functions, classes, keywords, etc. 

The help function has the following syntax:

help([object])

Python help() function arguments

object: Call help of the given object.

Example

Let us check the documentation of the print function in the python console. 

help(print)

Output:

Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

 iter() method

python iter() method returns the iterator object, it is used to convert an iterable to the iterator.

Syntax : iter(obj, sentinel)

Parameters : 

  • obj : Object which has to be converted to iterable ( usually an iterator ).
  • sentinel : value used to represent end of sequence.
# Python3 code to demonstrate
# working of iter()
 
# initializing list
lis1 = [1, 2, 3, 4, 5]
 
# printing type
print("The list is of type : " + str(type(lis1)))
 
# converting list using iter()
lis1 = iter(lis1)
 
# printing type
print("The iterator is of type : " + str(type(lis1)))
 
# using next() to print iterator values
print(next(lis1))
print(next(lis1))
print(next(lis1))
print(next(lis1))
print(next(lis1))
Output
The list is of type : <class 'list'>
The iterator is of type : <class 'list_iterator'>
1
2
3
4

property() function

Python property() function returns the object of the property class and it is used to create property of a class. 

Syntax: property(fget, fset, fdel, doc)

Parameters: 

  • fget() – used to get the value of attribute
  • fset() – used to set the value of attribute
  • fdel() – used to delete the attribute value
  • doc() – string that contains the documentation (docstring) for the attribute
# Python program to explain property() function
# Alphabet class
 
class Alphabet:
    def __init__(self, value):
        self._value = value
 
    # getting the values
    def getValue(self):
        print('Getting value')
        return self._value
 
    # setting the values
    def setValue(self, value):
        print('Setting value to ' + value)
        self._value = value
 
    # deleting the values
    def delValue(self):
        print('Deleting value')
        del self._value
 
    value = property(getValue, setValue,
                     delValue, )
 
 
# passing the value
x = Alphabet('G')
print(x.value)
 
x.value = 'GfG'
 
del x.value

Output: 

Getting value
G
Setting value to GfG

Deleting value 

super()

The Python super() function returns objects represented in the parent’s class and is very useful in  multiple and multilevel inheritances to find which class the child class is extending first.

Syntax of super() in Python

Syntax: super()

Return : Return a proxy object which repre

sents the parent’s class.

# code
class Person:
 
    # Constructor
    def __init__(self, name, id):
        self.name = name
        self.id = id
 
    # To check if this person is an employee
    def Display(self):
        print(self.name, self.id)
     
 
class Emp(Person):
     
    def __init__(self, name, id):
        self.name_ = name
 
    def Print(self):
        print("Emp class called")
 
Emp_details = Emp("Mayank", 103)
 
# calling parent class function
Emp_details.name_, Emp_details.name

Output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-46ffda859ba6> in <module>
     24 
     25 # calling parent class function
---> 26 Emp_details.name_, Emp_details.name

AttributeError: 'Emp' object has no attribute 'name'

 

You may like these posts

  •  globals() functionglobals() function in Python returns the dictionary of current global symbol table.Symbol table: Symbol table is a data structure which contains a…

Post a Comment

© 2025Python . The Best Codder All rights reserved. Distributed by