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.
Output:
15
hasattr() Function
The python hasattr() function returns true if an object has given named attribute. Otherwise, it returns false.
Signature
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().
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
- Python3
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.)
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
- Python3
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.
- Python3
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
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.
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
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.
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
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.
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
- Python3
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
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.
- Python3
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
- Python3
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.
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.
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.
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
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
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
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.
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.
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:
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.
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.
- Python3
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.
OutputThe 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
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.
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'