This Class offers the formatting services beneficial for the implementation of functions similar to the built-in the
repr()
function. This class also has size limits for various object types to avoid the generation of excessively long representations.
Moreover, along with the size-limiting tools, this module also offers a decorator to detect recursive calls to
__repr__()
and substitute a placeholder string.
# importing the required module
from reprlib import recursive_repr
# defining the class
class TheList(list):
# using the decorator
@recursive_repr()
# defining the function
def __repr__(self):
return ''
# instantiating the class
one = TheList('abc')
# appending elements to the list
one.append(one)
one.append('x')
# printing the final list
print(one)
In the above snippet of code, we have imported the required module and defined a class as
TheList
. We have then used the decorator and defined the function as
__repr__()
that returns the
fillvalue
. We have then instantiated the class and appended elements to the list. At last, we have printed the list.
S. No.
Methods/Variables
Descriptions
Repr.maxlevel
This object type represents the depth limit for the recursive representation. The default value is 6.
Repr.maxlong
This object type consists of the maximum number to represent the long value. The default value is 40.
Repr.maxstring
This object type limits the number of characters in a string-type object. The default value is 30.
Repr.maxother
This object type limits the size of some other data, where formatting is not specified.
Repr.repr(obj)
This method serves the same purpose as the built-in repr() method.
Repr.repr1(obj, level)
This method is a recursive implementation of the repr() method. Moreover, we have to specify the level for the recursive output.
There are some other max limits for dict, lists, tuples, sets, array and many more.
# importing the required modules
import reprlib
import math
# creating a list of factorials using the functions of the math library
factList = [math.factorial(x) for x in range(100)]
print(reprlib.repr(factList))
# creating the Repr object and set long size to 15
myRept = reprlib.Repr()
# using maxlong
myRept.maxlong = 15
print(myRept.repr(factList[53]))
[1, 1, 2, 6, 24, 120, ...]
427488...000000
Explanation:
In the above snippet of code, we have imported the required libraries and defined a list containing the factorials of numbers ranging from 0 to 100. and printed the value of the repr() function. We created the Repr object and set the long size to 15 using the maxlong object type. At last, we have again printed the result of the repr() function.
Next TopicHow to take Multiple Input from User in Python