Python Points
Python Points
Python Points
Memory Management
Memory management in Python involves a private heap containing all Python objects and data
structures. The management of this private heap is ensured internally by the Python memory
manager. The Python memory manager has different components which deal with various dynamic
storage management aspects, like sharing, segmentation, preallocation or caching.
The PYTHONMALLOC environment variable can be used to configure the memory allocators used
by Python.
• malloc: use the malloc() function of the C library for all domains
(PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, PYMEM_DOMAIN_OBJ).
The PYTHONMALLOCSTATS environment variable can be used to print statistics of the pymalloc
memory allocator every time a new pymalloc object arena is created, and on shutdown.
We use above module (monk) in below code and change behavior of func() at run-time by assigning
different value.
import monk
def monkey_f(self):
print ("monkey_f() is being called")
# replacing address of "func" with "monkey_f"
monk.A.func = monkey_f
obj = monk.A()
# calling function "func" whose address got replaced
# with function "monkey_f()"
obj.func()
Examples:
Output :monkey_f() is being called
1. pickle.HIGHEST_PROTOCOL
This is an integer value representing the highest protocol version available. This is
considered as the protocol value which is passed to the functions dump(), dumps().
2. pickle.DEFAULT_PROTOCOL
This is an integer value representing the default protocol used for pickling whose value may
be less than the value of the highest protocol.
Functions provided by the pickle module :
1. pickle.dump(obj, file, protocol = None, *, fix_imports = True)
This function is equivalent to Pickler(file, protocol).dump(obj). This is used to write a
pickled representation of obj to the open file object file.
The optional protocol argument is an integer that tells the pickler to use the given protocol.
The supported protocols are 0 to HIGHEST_PROTOCOL. If not specified, the default is
DEFAULT_PROTOCOL. If a negative number is specified, HIGHEST_PROTOCOL is
selected.
If fix_imports is true and protocol is less than 3, the pickle will try to map the new Python 3
names to the old module names used in Python 2, so that the pickle data stream is readable
with Python 2.
Python - Magic or Dunder Methods
Magic methods in Python are the special methods that start and end with the double underscores.
They are also called dunder methods. Magic methods are not meant to be invoked directly by you,
but the invocation happens internally from the class on a certain action. For example, when you add
two numbers using the + operator, internally, the __add__() method will be called.
Built-in classes in Python define many magic methods. Use the dir() function to see the number
of magic methods inherited by a class. For example, the following lists all the attributes and
methods defined in the int class.
>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__',
'__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__',
'__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__',
'__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__',
'__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__',
'__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__',
'__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__',
'__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__',
'__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate',
'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
__new__() method
Languages such as Java and C# use the new operator to create a new instance of a class. In Python
the __new__() magic method is implicitly called before the __init__() method. The
__new__() method returns a new object, which is then initialized by __init__().
Example: __new__()
class Employee:
def __new__(cls):
print ("__new__ magic method is called")
inst = object.__new__(cls)
return inst
def __init__(self):
print ("__init__ magic method is called")
self.name='Satya'
The above example will produce the following output when you create an instance of the
Employee class.
>>> emp = Employee()
__new__ magic method is called
__init__ magic method is called
Thus, the __new__() method is called before the __init__() method.
__str__() method
Another useful magic method is __str__(). It is overridden to return a printable string
representation of any user defined class. We have seen str() built-in function which returns a
string from the object parameter. For example, str(12) returns '12'. When invoked, it calls the
__str__() method in the int class.
>>> num=12
>>> str(num)
'12'
>>> #This is equivalent to
>>> int.__str__(num)
'12'
After a name
Python has their by default keywords which we can not use as the variable
name. To avoid such conflict between python keyword and variable we use
underscore after name
Example:
>>> class MyClass():
... def __init__(self):
... print ("OWK")
>>> def my_defination(var1 = 1, class_ = MyClass):
... print (var1)
... print (class_)
>>> my_defination()
1
__main__.MyClass
>>>
Before a name
Leading Underscore before variable/function/method name indicates to
programmer that It is for internal use only, that can be modified whenever
class want.
Here name prefix by underscore is treated as non-public. If specify from
Import * all the name starts with _ will not import. Python does not
specify truly private so this ones can be call directly from other modules if
it is specified in __all__, We also call it weak Private
class Prefix:
... def __init__(self):
... self.public = 10
... self._private = 12
>>> test = Prefix()
>>> test.public
10
>>> test._private
12
Python class_file.py
def public_api():
print ("public api")
def _private_api():
print ("private api")
Double Underscore(__)
__leading_double_underscore
Leading double underscore tell python interpreter to rewrite name in order
to avoid conflict in subclass.Interpreter changes variable name with class
extension and that feature known as the Mangling.
testFile.py
class Myclass():
def __init__(self):
self.__variable = 10
Prerequisite: Underscore in Python