Sign In
Sign In

Dunder Methods in Python: Purpose and Application

Dunder Methods in Python: Purpose and Application
Hostman Team
Technical writer
Python
10.02.2025
Reading time: 21 min

Dunder methods (double underscore methods) are special methods in the Python programming language that are surrounded by two underscores at the beginning and end of their names. This naming convention is intended to prevent name conflicts with other user-defined functions.

Each dunder method corresponds to a specific Python language construct that performs a particular data transformation operation.

Here are some commonly used dunder methods:

  • __init__(): Initializes an instance of a class, acting as a constructor.
  • __repr__(): Returns a representative value of a variable in Python expression format.
  • __eq__(): Compares two variables.

Whenever the Python interpreter encounters any syntactic construct, it implicitly calls the corresponding dunder method with all necessary arguments.

For example, when Python encounters the addition symbol in the expression a + b, it implicitly calls the dunder method a.__add__(b), where the addition operation is performed internally.

Thus, dunder methods implement the core mechanics of the Python language. Importantly, these methods are accessible not only to the interpreter but also to ordinary users. Moreover, you can override the implementation of each dunder method within custom classes.

In this guide, we'll explore all existing dunder methods in Python and provide examples.

The demonstrated scripts were run using the Python 3.10.12 interpreter installed on a Hostman cloud server running Ubuntu 22.04.

To run examples from this article, you need to place each script in a separate file with a .py extension (e.g., some_script.py). Then you can execute the file with the following command:

python some_script.py

Creation, Initialization, and Deletion

Creation, initialization, and deletion are the main stages of an object's lifecycle in Python. Each of these stages corresponds to a specific dunder method.

Syntax

Dunder Method

Result

Description

a = C(b, c)

C.__new__(b, c)

C

Creation

a = C(b, c)

C.__init__(b, c)

None

Initialization

del a

a.__del__()

None

Deletion

The general algorithm for these methods has specific characteristics:

  • Creation: The __new__() method is called with a set of arguments. The first argument is the class of the object (not the object itself). This name is not regulated and can be arbitrary. The remaining arguments are the parameters specified when creating the object in the calling code. The __new__() method must return a class instance — a new object.

  • Initialization: Immediately after returning a new object from __new__(), the __init__() method is automatically called. Inside this method, the created object is initialized. The first argument is the object itself, passed as self. The remaining arguments are the parameters specified when creating the object. The first argument name is regulated and must be the keyword self.

  • Deletion: Explicit deletion of an object using the del keyword triggers the __del__() method. Its only argument is the object itself, accessed through the self keyword.

Thanks to the ability to override dunder methods responsible for an object's lifecycle, you can create unique implementations for custom classes:

class Initable:
	instances = 0  # class variable, not an object variable

	def __new__(cls, first, second):
		print(cls.instances)
		cls.instances += 1
		return super().__new__(cls)  # call the base class's object creation method with the current class name as an argument

	def __init__(self, first, second):
		self.first = first  # object variable
		self.second = second  # another object variable

	def __del__(self):
		print("Annihilated!")

inited = Initable("Initialized", 13)  # output: 0

print(inited.first)  # output: Initialized
print(inited.second)  # output: 13

del inited  # output: Annihilated!

Thanks to these hook-like methods, you can manage not only the internal state of an object but also external resources.

Comparison

Objects created in Python can be compared with one another, yielding either a positive or negative result. Each comparison operator is associated with a corresponding dunder method.

Syntax

Dunder Method

Result

Description

a == b or a is b

a.__eq__(b)

bool

Equal

a != b

a.__ne__(b)

bool

Not equal

a > b

a.__gt__(b)

bool

Greater than

a < b

a.__lt__(b)

bool

Less than

a >= b

a.__ge__(b)

bool

Greater than or equal

a <= b

a.__le__(b)

bool

Less than or equal

hash(a)

a.__hash__()

int

Hashing

In some cases, Python provides multiple syntactic constructs for the same comparison operations. We can replace each of these operations by the corresponding dunder method:

a = 5
b = 6
c = "This is a regular string"

print(a == b)  # Output: False
print(a is b)  # Output: False
print(a.__eq__(b))  # Output: False

print(a != b)  # Output: True
print(a is not b)  # Output: True
print(a.__ne__(b))  # Output: True
print(not a.__eq__(b))  # Output: True

print(a > b)  # Output: False
print(a < b)  # Output: True
print(a >= b)  # Output: False
print(a <= b)  # Output: True

print(a.__gt__(b))  # Output: False
print(a.__lt__(b))  # Output: True
print(a.__ge__(b))  # Output: False
print(a.__le__(b))  # Output: True

print(hash(a))  # Output: 5
print(a.__hash__())  # Output: 5

print(c.__hash__())  # Output: 1745008793

The __ne__() method returns the inverted result of the __eq__() method. Because of this, there's often no need to redefine __ne__() since the primary comparison logic is usually implemented in __eq__().

Additionally, some comparison operations implicitly performed by Python when manipulating list elements require hash computation. For this purpose, Python provides the special dunder method __hash__().

By default, any user-defined class already implements the methods __eq__(), __ne__(), and __hash__():

class Comparable:
	def __init__(self, value1, value2):
		self.value1 = value1
		self.value2 = value2

c1 = Comparable(4, 3)
c2 = Comparable(7, 9)

print(c1 == c1)  # Output: True
print(c1 != c1)  # Output: False

print(c1 == c2)  # Output: False
print(c1 != c2)  # Output: True

print(c1.__hash__())  # Example output: -2146408067
print(c2.__hash__())  # Example output: 1076316

In this case, the default __eq__() method compares instances without considering their internal variables defined in the __init__() constructor. The same applies to the __hash__() method, whose results vary between calls.

Python's mechanics are designed such that overriding the __eq__() method automatically removes the default __hash__() method:

class Comparable:
	def __init__(self, value1, value2):
		self.value1 = value1
		self.value2 = value2

	def __eq__(self, other):
		if isinstance(other, self.__class__):
			return self.value1 == other.value1 and self.value2 == other.value2
		return False

c1 = Comparable(4, 3)
c2 = Comparable(7, 9)

print(c1 == c1)  # Output: True
print(c1 != c1)  # Output: False

print(c1 == c2)  # Output: False
print(c1 != c2)  # Output: True

print(c1.__hash__())  # ERROR (method not defined)
print(c2.__hash__())  # ERROR (method not defined)

Therefore, overriding the __eq__() method requires also overriding the __hash__() method with a new hashing algorithm:

class Comparable:
	def __init__(self, value1, value2):
		self.value1 = value1
		self.value2 = value2

	def __eq__(self, other):
		if isinstance(other, self.__class__):
			return self.value1 == other.value1 and self.value2 == other.value2
		return False

	def __ne__(self, other):
		return not self.__eq__(other)

	def __gt__(self, other):
		return self.value1 + self.value2 > other.value1 + other.value2

	def __lt__(self, other):
		return not self.__gt__(other)

	def __ge__(self, other):
		return self.value1 + self.value2 >= other.value1 + other.value2

	def __le__(self, other):
		return self.value1 + self.value2 <= other.value1 + other.value2

	def __hash__(self):
		return hash((self.value1, self.value2))  # Returns the hash of a tuple of two numbers

c1 = Comparable(4, 3)
c2 = Comparable(7, 9)

print(c1 == c1)  # Output: True
print(c1 != c1)  # Output: False

print(c1 == c2)  # Output: False
print(c1 != c2)  # Output: True

print(c1 > c2)  # Output: False
print(c1 < c2)  # Output: True

print(c1 >= c2)  # Output: False
print(c1 <= c2)  # Output: True

print(c1.__hash__())  # Output: -1441980059
print(c2.__hash__())  # Output: -2113571365

Thus, by overriding comparison methods, you can use standard syntactic constructs for custom classes, similar to built-in data types, regardless of their internal complexity.

Conversion in Python

In Python, we can convert all built-in types from one to another. Similar conversions can be added to custom classes, considering the specifics of their internal implementation.

Syntax

Dunder Method

Result

Description

str(a)

a.__str__()

str

String

bool(a)

a.__bool__()

bool

Boolean

int(a)

a.__int__()

int

Integer

float(a)

a.__float__()

float

Floating-point number

bytes(a)

a.__bytes__()

bytes

Byte sequence

complex(a)

a.__complex__()

complex

Complex number

By default, we can only convert a custom class to a few basic types:

class Convertible:
    def __init__(self, value1, value2):
        self.value1 = value1
        self.value2 = value2

some_variable = Convertible(4, 3)

print(str(some_variable))  # Example output: <__main__.Convertible object at 0x1229620>
print(bool(some_variable))  # Output: True

However, by overriding the corresponding dunder methods, you can implement conversions from a custom class to any built-in data type:

class Convertible:
	def __init__(self, value1, value2):
		self.value1 = value1
		self.value2 = value2

	def __str__(self):
		return str(self.value1) + str(self.value2)

	def __bool__(self):
		return self.value1 == self.value2

	def __int__(self):
		return self.value1 + self.value2

	def __float__(self):
		return float(self.value1) + float(self.value2)

	def __bytes__(self):
		return bytes(self.value1) + bytes(self.value2)

	def __complex__(self):
		return complex(self.value1) + complex(self.value2)

someVariable = Convertible(4, 3)

print(str(someVariable)) # output: 43
print(bool(someVariable)) # output: False
print(int(someVariable)) # output: 7
print(float(someVariable)) # output: 7.0
print(bytes(someVariable)) # output: b'\x00\x00\x00\x00\x00\x00\x00'
print(complex(someVariable)) # output: (7+0j)

Thus, implementing dunder methods for conversion allows objects of custom classes to behave like built-in data types, enhancing their completeness and versatility.

Element Management in Python

Just like lists, we can make any custom class in Python iterable. Python provides corresponding dunder methods for retrieving and manipulating elements.

Syntax

Dunder Method

Description

len(a)

a.__len__()

Length

iter(a) or for i in a:

a.__iter__()

Iterator

a[b]

a.__getitem__(b)

Retrieve element

a[b]

a.__missing__(b)

Retrieve non-existent dictionary item

a[b] = c

a.__setitem__(b, c)

Set element

del a[b]

a.__delitem__(b)

Delete element

b in a

a.__contains__(b)

Check if element exists

reversed(a)

a.__reversed__()

Elements in reverse order

next(a)

a.__next__()

Retrieve next element

Even though the internal implementation of an iterable custom class can vary, element management is handled using Python's standard container interface rather than custom methods.

class Iterable:
	def __init__(self, e1, e2, e3, e4):
		self.e1 = e1
		self.e2 = e2
		self.e3 = e3
		self.e4 = e4
		self.index = 0

	def __len__(self):
		len = 0
		if self.e1: len += 1
		if self.e2: len += 1
		if self.e3: len += 1
		if self.e4: len += 1
		return len

	def __iter__(self):
		for i in range(0, self.__len__() + 1):
			if i == 0: yield self.e1
			if i == 1: yield self.e2
			if i == 2: yield self.e3
			if i == 3: yield self.e4

	def __getitem__(self, item):
		if item == 0: return self.e1
		elif item == 1: return self.e2
		elif item == 2: return self.e3
		elif item == 3: return self.e4
		else: raise Exception("Out of range")

	def __setitem__(self, item, value):
		if item == 0: self.e1 = value
		elif item == 1: self.e2 = value
		elif item == 2: self.e3 = value
		elif item == 3: self.e4 = value
		else: raise Exception("Out of range")

	def __delitem__(self, item):
		if item == 0: self.e1 = None
		elif item == 1: self.e2 = None
		elif item == 2: self.e3 = None
		elif item == 3: self.e4 = None
		else: raise Exception("Out of range")

	def __contains__(self, item):
		if self.e1 == item: return true
		elif self.e2 == item: return True
		elif self.e3 == item: return True
		elif self.e4 == item: return True
		else: return False

	def __reversed__(self):
		return Iterable(self.e4, self.e3, self.e2, self.e1)

	def __next__(self):
		if self.index >=4: self.index = 0
		if self.index == 0: element = self.e1
		if self.index == 1: element = self.e2
		if self.index == 2: element = self.e3
		if self.index == 3: element = self.e4
		self.index += 1
		return element

someContainer = Iterable(-2, 54, 6, 13)

print(someContainer.__len__()) # output: 4

print(someContainer[0]) # output: -2
print(someContainer[1]) # output: 54
print(someContainer[2]) # output: 6
print(someContainer[3]) # output: 13

someContainer[2] = 117
del someContainer[0]

print(someContainer[2]) # output: 117

for element in someContainer:
	print(element) # output: None, 54, 117, 13

print(117 in someContainer) # output: True

someContainerReversed = someContainer.__reversed__()

for element in someContainerReversed:
	print(element) # output: 13, 117, 54, None

print(someContainer.__next__()) # output: None
print(someContainer.__next__()) # output: 54
print(someContainer.__next__()) # output: 117
print(someContainer.__next__()) # output: 13
print(someContainer.__next__()) # output: None

It’s important to understand the difference between the __iter__() and __next__() methods, which facilitate object iteration.

  • __iter__() iterates the object at a given point.
  • __next__() returns an element considering an internal index.

A particularly interesting dunder method is __missing__(), which is only relevant in custom classes inherited from the base dictionary type dict.

This method allows you to override the default dict behavior when attempting to retrieve a non-existent element:

class dict2(dict):
	def __missing__(self, item):
		return "Sorry but I don’t exist..."

someDictionary = dict2(item1=10, item2=20, item3=30)

print(someDictionary["item1"]) # output: 10
print(someDictionary["item2"]) # output: 20
print(someDictionary["item3"]) # output: 30
print(someDictionary["item4"]) # output: Sorry but I don’t exist...

Arithmetic Operations

Arithmetic operations are the most common type of data manipulation. Python provides corresponding syntactic constructs for performing addition, subtraction, multiplication, and division.

Most often, left-handed methods are used, which perform calculations on behalf of the left operand.

Syntax

Dunder Method

Description

a + b

a.__add__(b)

Addition

a - b

a.__sub__(b)

Subtraction

a * b

a.__mul__(b)

Multiplication

a / b

a.__truediv__(b)

Division

a % b

a.__mod__(b)

Modulus

a // b

a.__floordiv__(b)

Floor division

a ** b

a.__pow__(b)

Exponentiation

If the right operand does not know how to perform the operation, Python automatically calls a right-handed method, which calculates the value on behalf of the right operand.

However, in this case, the operands must be of different types.

Syntax

Dunder Method

Description

a + b

a.__radd__(b)

Addition

a - b

a.__rsub__(b)

Subtraction

a * b

a.__rmul__(b)

Multiplication

a / b

a.__rtruediv__(b)

Division

a % b

a.__rmod__(b)

Modulus

a // b

a.__rfloordiv__(b)

Floor Division

a ** b

a.__rpow__(b)

Exponentiation

It is also possible to override in-place arithmetic operations. In this case, dunder methods do not return a new value but modify the existing variables of the left operand.

Syntax

Dunder Method

Description

a += b

a.__iadd__(b)

Addition

a -= b

a.__isub__(b)

Subtraction

a *= b

a.__imul__(b)

Multiplication

a /= b

a.__itruediv__(b)

Division

a %= b

a.__imod__(b)

Modulus

a //= b

a.__ifloordiv__(b)

Floor Division

a **= b

a.__ipow__(b)

Exponentiation

By overriding these corresponding dunder methods, you can define specific behaviors for your custom class during arithmetic operations:

class Arithmetic:
	def __init__(self, value1, value2):
		self.value1 = value1
		self.value2 = value2

	def __add__(self, other):
		return Arithmetic(self.value1 + other.value1, self.value2 + other.value2)

	def __radd__(self, other):
		return Arithmetic(other + self.value1, other + self.value2)

	def __iadd__(self, other):
		self.value1 += other.value1
		self.value2 += other.value2
		return self

	def __sub__(self, other):
		return Arithmetic(self.value1 - other.value1, self.value2 - other.value2)

	def __rsub__(self, other):
		return Arithmetic(other - self.value1, other - self.value2)

	def __isub__(self, other):
		self.value1 -= other.value1
		self.value2 -= other.value2
		return self

	def __mul__(self, other):
		return Arithmetic(self.value1 * other.value1, self.value2 * other.value2)

	def __rmul__(self, other):
		return Arithmetic(other * self.value1, other * self.value2)

	def __imul__(self, other):
		self.value1 *= other.value1
		self.value2 *= other.value2
		return self

	def __truediv__(self, other):
		return Arithmetic(self.value1 / other.value1, self.value2 / other.value2)

	def __rtruediv__(self, other):
		return Arithmetic(other / self.value1, other / self.value2)

	def __itruediv__(self, other):
		self.value1 /= other.value1
		self.value2 /= other.value2
		return self

	def __mod__(self, other):
		return Arithmetic(self.value1 % other.value1, self.value2 % other.value2)

	def __rmod__(self, other):
		return Arithmetic(other % self.value1, other % self.value2)

	def __imod__(self, other):
		self.value1 %= other.value1
		self.value2 %= other.value2
		return self

	def __floordiv__(self, other):
		return Arithmetic(self.value1 // other.value1, self.value2 // other.value2)

	def __rfloordiv__(self, other):
		return Arithmetic(other // self.value1, other // self.value2)

	def __ifloordiv__(self, other):
		self.value1 //= other.value1
		self.value2 //= other.value2
		return self

	def __pow__(self, other):
		return Arithmetic(self.value1 ** other.value1, self.value2 ** other.value2)

	def __rpow__(self, other):
		return Arithmetic(other ** self.value1, other ** self.value2)

	def __ipow__(self, other):
		self.value1 **= other.value1
		self.value2 **= other.value2
		return self

a1 = Arithmetic(4, 6)
a2 = Arithmetic(10, 3)

add = a1 + a2
sub = a1 - a2
mul = a1 * a2
truediv = a1 / a2
mod = a1 % a2
floordiv = a1 // a2
pow = a1 ** a2

radd = 50 + a1
rsub = 50 - a2
rmul = 50 * a1
rtruediv = 50 / a2
rmod = 50 % a1
rfloordiv = 50 // a2
rpow = 50 ** a2

a1 -= a2
a1 *= a2
a1 /= a2
a1 %= a2
a1 //= a2
a1 **= a2

print(add.value1, add.value2) # output: 14 9
print(sub.value1, sub.value2) # output: -6 3
print(mul.value1, mul.value2) # output: 40 18
print(truediv.value1, truediv.value2) # output: 0.4 2.0
print(mod.value1, mod.value2) # output: 4 0
print(floordiv.value1, floordiv.value2) # output: 0 2
print(pow.value1, pow.value2) # output: 1048576 216

print(radd.value1, radd.value2) # output: 54 56
print(rsub.value1, rsub.value2) # output: 40 47
print(rmul.value1, rmul.value2) # output: 200 300
print(rtruediv.value1, rtruediv.value2) # output: 5.0 16.666666666666668
print(rmod.value1, rmod.value2) # output: 2 2
print(rfloordiv.value1, rfloordiv.value2) # output: 5 16
print(rpow.value1, rpow.value2) # output: 97656250000000000 125000

In real-world scenarios, arithmetic dunder methods are among the most frequently overridden. Therefore, it is good practice to implement both left-handed and right-handed methods simultaneously.

Bitwise Operations

In addition to standard mathematical operations, Python allows you to override the behavior of custom classes during bitwise transformations.

Syntax

Dunder Method

Description

a & b

a.__and__(b)

Bitwise AND

`a

b`

a.__or__(b)

a ^ b

a.__xor__(b)

Bitwise XOR

a >> b

a.__rshift__(b)

Right Shift

a << b

a.__lshift__(b)

Left Shift

Similar to arithmetic operations, bitwise transformations can be performed on behalf of the right operand.

Syntax

Dunder Method

Description

a & b

a.__rand__(b)

Bitwise AND

`a

b`

a.__ror__(b)

a ^ b

a.__rxor__(b)

Bitwise XOR

a >> b

a.__rrshift__(b)

Right Shift

a << b

a.__rlshift__(b)

Left Shift

Naturally, bitwise operations can also be performed in-place, modifying the left operand instead of returning a new object.

Syntax

Dunder Method

Description

a &= b

a.__iand__(b)

Bitwise AND

`a

= b`

a.__ior__(b)

a ^= b

a.__ixor__(b)

Bitwise XOR

a >>= b

a.__irshift__(b)

Right Shift

a <<= b

a.__ilshift__(b)

Left Shift

By overriding these dunder methods, any custom class can perform familiar bitwise operations on its contents seamlessly.

class Bitable:
	def __init__(self, value1, value2):
		self.value1 = value1
		self.value2 = value2

	def __and__(self, other):
		return Bitable(self.value1 & other.value1, self.value2 & other.value2)

	def __rand__(self, other):
		return Bitable(other & self.value1, other & self.value2)

	def __iand__(self, other):
		self.value1 &= other.value1
		self.value2 &= other.value2
		return self

	def __or__(self, other):
		return Bitable(self.value1 | other.value1, self.value2 | other.value2)

	def __ror__(self, other):
		return Bitable(other | self.value1, other | self.value2)

	def __ior__(self, other):
		self.value1 |= other.value1
		self.value2 |= other.value2
		return self

	def __xor__(self, other):
		return Bitable(self.value1 ^ other.value1, self.value2 ^ other.value2)

	def __rxor__(self, other):
		return Bitable(other ^ self.value1, other ^ self.value2)

	def __ixor__(self, other):
		self.value1 |= other.value1
		self.value2 |= other.value2
		return self

	def __rshift__(self, other):
		return Bitable(self.value1 >> other.value1, self.value2 >> other.value2)

	def __rrshift__(self, other):
		return Bitable(other >> self.value1, other >> self.value2)

	def __irshift__(self, other):
		self.value1 >>= other.value1
		self.value2 >>= other.value2
		return self

	def __lshift__(self, other):
		return Bitable(self.value1 << other.value1, self.value2 << other.value2)

	def __rlshift__(self, other):
		return Bitable(other << self.value1, other << self.value2)

	def __ilshift__(self, other):
		self.value1 <<= other.value1
		self.value2 <<= other.value2
		return self

b1 = Bitable(5, 3)
b2 = Bitable(7, 2)

resultAnd = b1 & b2
resultOr = b1 | b2
resultXor = b1 ^ b2
resultRshift = b1 >> b2
resultLshift = b1 << b2

resultRand = 50 & b1
resultRor = 50 | b2
resultRxor = 50 ^ b1
resultRrshift = 50 >> b2
resultRlshift = 50 << b1

b1 &= b2
b1 |= b2
b1 ^= b2
b1 >>= b2
b1 <<= b2

print(resultAnd.value1, resultAnd.value2) # output: 5 2
print(resultOr.value1, resultAnd.value2) # output: 7 2
print(resultXor.value1, resultAnd.value2) # output: 2 2
print(resultRshift.value1, resultAnd.value2) # output: 0 2
print(resultLshift.value1, resultAnd.value2) # output: 640 2

print(resultRand.value1, resultRand.value2) # output: 0 2
print(resultRor.value1, resultRor.value2) # output: 55 50
print(resultRxor.value1, resultRxor.value2) # output: 55 49
print(resultRrshift.value1, resultRrshift.value2) # output: 0 12
print(resultRlshift.value1, resultRlshift.value2) # output: 1600 400

In addition to operations involving two operands, Python provides dunder methods for bitwise transformations involving a single operand.

Syntax

Dunder Method

Description

-a

a.__neg__()

Negation

~a

a.__invert__()

Bitwise Inversion

+a

a.__pos__()

Bitwise Positivization

The + operator typically does not affect the value of the variable. Many classes override this method to perform alternative transformations.

Object Information Extraction

Python offers several dunder methods to retrieve additional information about an object.

Syntax

Dunder Method

Description

str(a)

a.__str__()

Returns the object's value

repr(a)

a.__repr__()

Returns the object's representation

  • __str__() returns a user-friendly string representation of the variable’s value.
  • __repr__() returns a more detailed and often code-like representation of the variable, suitable for recreating the original variable via eval().

So, it is important for a custom class to be able to provide additional information about itself.

class Human:
	def __init__(self, name, age):
		self.name = name
		self.age = age

	def __str__(self):
		return str(self.name + " (" + str(self.age) + " years old)")

	def __repr__(self):
		return "Human(" + repr(self.name) + ", " + str(self.age) + ")"

someHuman = Human("John", 35)
someOtherHuman = eval(repr(someHuman))

print(str(someHuman)) # output: John (35 years old)
print(repr(someHuman)) # output: Human('John', 35)

print(str(someOtherHuman)) # output: John (35 years old)
print(repr(someOtherHuman)) # output: Human('John', 35)

Conclusion

A distinctive feature of Python dunder methods is using two underscore characters at the beginning and end of the name, which prevents naming conflicts with other user-defined functions.

Unlike regular control methods, dunder methods allow you to define unique behavior for a custom class when using standard Python operators responsible for:

  • Arithmetic operations
  • Iteration and access to elements
  • Creation, initialization, and deletion of objects

Additional dunder attributes provide auxiliary information about Python program entities, which can simplify the implementation of custom classes.

Python
10.02.2025
Reading time: 21 min

Similar

Python

Understanding the main() Function in Python

In any complex program, it’s crucial to organize the code properly: define a starting point and separate its logical components. In Python, modules can be executed on their own or imported into other modules, so a well‑designed program must detect the execution context and adjust its behavior accordingly.  Separating run‑time code from import‑time code prevents premature execution, and having a single entry point makes it easier to configure launch parameters, pass command‑line arguments, and set up tests. When all important logic is gathered in one place, adding automated tests and rolling out new features becomes much more convenient.  For exactly these reasons it is common in Python to create a dedicated function that is called only when the script is run directly. Thanks to it, the code stays clean, modular, and controllable. That function, usually named main(), is the focus of this article. All examples were executed with Python 3.10.12 on a Hostman cloud server running Ubuntu 22.04. Each script was placed in a separate .py file (e.g., script.py) and started with: python script.py The scripts are written so they can be run just as easily in any online Python compiler for quick demonstrations. What Is the main() Function in Python The simplest Python code might look like: print("Hello, world!")  # direct execution Or a script might execute statements in sequence at file level: print("Hello, world!")       # action #1 print("How are you, world?") # action #2 print("Good‑bye, world...")  # action #3 That trivial arrangement works only for the simplest scripts. As a program grows, the logic quickly becomes tangled and demands re‑organization: # function containing the program’s main logic (entry point) def main():     print("Hello, world!") # launch the main logic if __name__ == "__main__":     main()                    # call the function with the main logic With more actions the code might look like: def main(): print("Hello, world!") print("How are you, world?") print("Good‑bye, world...") if __name__ == "__main__": main() This implementation has several important aspects, discussed below. The main() Function The core program logic lives inside a separate function. Although the name can be anything, developers usually choose main, mirroring C, C++, Java, and other languages.  Both helper code and the main logic are encapsulated: nothing sits “naked” at file scope. # greeting helper def greet(name): print(f"Hello, {name}!") # program logic def main(): name = input("Enter your name: ") greet(name) # launch the program if __name__ == "__main__": main() Thus main() acts as the entry point just as in many other languages. The if __name__ == "__main__" Check Before calling main() comes the somewhat odd construct if __name__ == "__main__":.  Its purpose is to split running from importing logic: If the script runs directly, the code inside the if block executes. If the script is imported, the block is skipped. Inside that block, you can put any code—not only the main() call: if __name__ == "__main__":     print("Any code can live here, not only main()") __name__ is one of Python’s built‑in “dunder” (double‑underscore) variables, often called magic or special. All dunder objects are defined and used internally by Python, but regular users can read them too. Depending on the context, __name__ holds: "__main__" when the module runs as a standalone script. The module’s own name when it is imported elsewhere. This lets a module discover its execution context. Advantages of Using  main() Organization Helper functions and classes, as well as the main function, are wrapped separately, making them easy to find and read. Global code is minimal—only initialization stays at file scope: def process_data(data): return [d * 2 for d in data] def main(): raw = [1, 2, 3, 4] result = process_data(raw) print("Result:", result) if __name__ == "__main__": main() A consistent style means no data manipulation happens at the file level. Even in a large script you can quickly locate the start of execution and any auxiliary sections. Isolation When code is written directly at the module level, every temporary variable, file handle, or connection lives in the global namespace, which can be painful for debugging and testing. Importing such a module pollutes the importer’s globals: # executes immediately on import values = [2, 4, 6] doubles = [] for v in values: doubles.append(v * 2) print("Doubled values:", doubles) With main() everything is local; when the function returns, its variables vanish: def double_list(items): return [x * 2 for x in items] # create a new list with doubled elements def main(): values = [2, 4, 6] result = double_list(values) print("Doubled values:", result) if __name__ == "__main__": main() That’s invaluable for unit testing, where you might run specific functions (including  main()) without triggering the whole program. Safety Without the __name__ check, top‑level code runs even on import—usually undesirable and potentially harmful. some.py: print("This code will execute even on import!") def useful_function(): return 42 main.py: import some print("The logic of the imported module executed itself...") Console: This code will execute even on import! The logic of the imported module executed itself... The safer some.py: def useful_function():     return 42 def main():     print("This code will not run on import") main() plus the __name__ check guard against accidental execution. Inside main() you can also verify user permissions or environment variables. How to Write main() in Python Remember: main() is not a language construct, just a regular function promoted to “entry point.” To ensure it runs only when the script starts directly: Tools – define helper functions with business logic. Logic – assemble them inside main() in the desired order. Check – add the if __name__ == "__main__" guard.  This template yields structured, import‑safe, test‑friendly code—excellent practice for any sizable Python project. Example Python Program Using main() # import the standard counter from collections import Counter # runs no matter how the program starts print("The text‑analysis program is active") # text‑analysis helper def analyze_text(text): words = text.split() # split text into words total = len(words) # total word count unique = len(set(words)) # unique word count avg_len = sum(len(w) for w in words) / total if total else 0 freq = Counter(words) # build frequency counter top3 = freq.most_common(3) # top three words return { 'total': total, 'unique': unique, 'avg_len': avg_len, 'top3': top3 } # program’s main logic def main(): print("Enter text (multiple lines). Press Enter on an empty line to finish:") lines = [] while True: line = input() if not line: break lines.append(line) text = ' '.join(lines) stats = analyze_text(text) print(f"\nTotal number of words: {stats['total']}") print(f"Unique words: {stats['unique']}") print(f"Average word length: {stats['avg_len']:.2f}") print("Top‑3 most frequent words:") for word, count in stats['top3']: print(f" {word!r}: {count} time(s)") # launch program if __name__ == "__main__": main() Running the script prints a prompt: Enter text (multiple lines). Press Enter on an empty line to finish: Input first line: Star cruiser Orion glided silently through the darkness of intergalactic space. Second line: Signals of unknown life‑forms flashed on the onboard sensors where the nebula glowed with a phosphorescent light. Third line: The cruiser checked the sensors, then the cruiser activated the defense system, and the cruiser returned to its course. Console output: The text‑analysis program is active Total number of words: 47 Unique words: 37 Average word length: 5.68 Top‑3 most frequent words: 'the': 7 time(s) 'cruiser': 4 time(s) 'of': 2 time(s) If you import this program (file program.py) elsewhere: import program         # importing program.py Only the code outside main() runs: The text‑analysis program is active So, a moderately complex text‑analysis utility achieves clear logic separation and context detection. When to Use main() and When Not To Use  main() (almost always appropriate) when: Medium/large scripts – significant code with non‑trivial logic, multiple functions/classes. Libraries or CLI utilities – you want parts of the module importable without side effects. Autotests – you need to test pure logic without extra boilerplate. You can skip main() when: Tiny one‑off scripts – trivial logic for a quick data tweak. Educational snippets – short examples illustrating a few syntax features. In short, if your Python program is a standalone utility or app with multiple processing stages, command‑line arguments, and external resources—introduce  main(). If it’s a small throw‑away script, omitting main() keeps things concise. Conclusion The  main() function in Python serves two critical purposes: Isolates the program’s core logic from the global namespace. Separates standalone‑execution logic from import logic. Thus, a Python file evolves from a straightforward script of sequential actions into a fully‑fledged program with an entry point, encapsulated logic, and the ability to detect its runtime environment.
14 July 2025 · 8 min to read
Python

Python Static Method

A static method in Python is bound to the class itself rather than any instance of that class. So, you can call it without first creating an object and without access to instance data (self).  To create a static method we need to use a decorator, specifically @staticmethod. It will tell Python to call the method on the class rather than an instance. Static methods are excellent for utility or helper functions that are logically connected to the class but don't need to access any of its properties.  When To Use & Not to Use a Python Static Method Static methods are frequently used in real-world code for tasks like input validation, data formatting, and calculations—especially when that logic naturally belongs with a class but doesn't need its state. Here's an example from a User class that checks email format: class User: @staticmethod def is_valid_email(email): return "@" in email and "." in email This method doesn't depend on any part of the User instance, but conceptually belongs in the class. It can be used anywhere as User.is_valid_email(email), keeping your code cleaner and more organized. If the logic requires access to or modification of instance attributes or class-level data, avoid using a static method as it won't help here. For instance, if you are working with user settings or need to monitor object creation, you will require a class method or an instance method instead. class Counter: count = 0 @classmethod def increment(cls): cls.count += 1 In this example, using a static method would prevent access to cls.count, making it useless for this kind of task. Python Static Method vs Class Method Though they look similar, class and static methods in Python have different uses; so, let's now quickly review their differences. Defined inside a class, a class method is connected to that class rather than an instance. Conventionally called cls, the class itself is the first parameter; so, it can access and change class-level data. Factory patterns, alternate constructors, or any activity applicable to the class as a whole and not individual instances are often implemented via class methods. Conversely, a static method is defined within a class but does not start with either self or cls parameters. It is just a regular function that “lives” inside a class but doesn’t interact with the class or its instances. For utility tasks that are conceptually related to the class but don’t depend on its state, static methods are perfect. Here's a quick breakdown of the Python class/static methods differences: Feature Class Method Static Method Binding Bound to the class Not bound to class or instance First parameter cls (class itself) None (no self or cls) Access to class/instance data Yes No Common use cases Factory methods, class-level behavior Utility/helper functions Decorator @classmethod @staticmethod Python Static Method vs Regular Functions You might ask: why not just define a function outside the class instead of using a static method? The answer is structure. A static method keeps related logic grouped within the class, even if it doesn't interact with the class or its instances. # Regular function def is_even(n): return n % 2 == 0 # Static method inside a class class NumberUtils: @staticmethod def is_even(n): return n % 2 == 0 Both functions do the same thing, but placing is_even inside NumberUtils helps keep utility logic organized and easier to find later. Let’s proceed to the hands-on Python static method examples. Example #1 Imagine that we have a MathUtils class that contains a static method for calculating the factorial: class MathUtils: @staticmethod def factorial(n): if n == 0: return 1 else: return n * MathUtils.factorial(n-1) Next, let's enter: print(MathUtils.factorial(5))120 We get the factorial of 5, which is 120. Here, the factorial static method does not use any attributes of the class instance, only the input argument n. And we called it using the MathUtils.factorial(n) syntax without creating an instance of the MathUtils class. In Python, static methods apply not only in classes but also in modules and packages. The @staticmethod decorator marks a function you define inside a class if it does not interact with instance-specific data. The function exists on its own; it is related to the class logically but is independent of its internal state. Managed solution for Backend development Example #2 Let's say we're working with a StringUtils module with a static method for checking if a string is a palindrome. The code will be: def is_palindrome(string):    return string == string[::-1] This function doesn't rely on any instance-specific data — it simply performs a check on the input. That makes it a good candidate for a static method. To organize it within a class and signal that it doesn't depend on the class state, we can use the @staticmethod decorator like this: class StringUtils:    @staticmethod    def is_palindrome(string):       return string == string[::-1] Let's enter for verification: print(StringUtils.is_palindrome("deed"))True print(StringUtils.is_palindrome("deer"))False That's correct, the first word is a palindrome, so the interpreter outputs True, but the second word is not, and we get False. So, we can call the is_palindrome method through the StringUtils class using the StringUtils.is_palindrome(string) syntax instead of importing the is_palindrome function and calling it directly. - Python static method and class instance also differ in that the static cannot affect the state of an instance. Since they do not have access to the instance, they cannot alter attribute values, which makes sense. Instance methods are how one may modify the instance state of a class. Example #3 Let's look at another example. Suppose we have a Person class that has an age attribute and a static is_adult method that checks the value against the age of majority: class Person:    def __init__(self, age):        self.age = age    @staticmethod    def is_adult(age):       return age >= 21 Next, let's create an age variable with a value of 24, call the is_adult static method from the Person class with this value and store its result in the is_adult variable, like this: age = 24is_adult = Person.is_adult(age) Now to test this, let's enter: print(is_adult)True Since the age matches the condition specified in the static method, we get True. In the example, the is_adult static method serves as an auxiliary tool—a helper function—accepting the age argument but without access to the age attribute of the Person class instance. Conclusion Static methods improve code readability and make it possible to reuse it. They are also more convenient when compared to standard Python functions. Static methods are convenient as, unlike functions, they do not call for a separate import. Therefore, applying Python class static methods can help you streamline and work with your code greatly. And, as you've probably seen from the examples above, they are quite easy to master. On our app platform you can find Python applications, such as Celery, Django, FastAPI and Flask. 
16 April 2025 · 6 min to read
Python

Input in Python

Python provides interactive capabilities through various tools, one of which is the input() function. Its primary purpose is to receive user input. This function makes Python programs meaningful because without user interaction, applications would have limited utility. How the Python Input Works This function operates as follows: user_name = input('Enter your name: ') user_age = int(input('How old are you? ')) First, the user is asked to enter their name, then their age. Both inputs are captured using a special operator that stores the entered values in the variables user_name and user_age. These values can then be used in the program. For example, we can create an age-based access condition for a website (by converting the age input to an integer using int()) and display a welcome message using the entered name: if user_age < 18: print('Sorry, access is restricted to adults only') else: print('Welcome to the site,', user_name, '!') So, what happens when int() receives an empty value? If the user presses Enter without entering anything, let's see what happens by extending the program: user_name = input('Enter your name: ') user_age = int(input('How old are you? ')) if user_age < 18: print('Sorry, access is restricted to adults only') else: print('Welcome to the site,', user_name, '!') input('Press Enter to go to the menu') print('Welcome to the menu') Pressing Enter moves the program to the next line of code. If there is no next line, the program exits. The last line can be written as: input('Press Enter to exit') If there are no more lines in the program, it will exit. Here is the complete version of the program: user_name = input('Enter your name: ') user_age = int(input('How old are you? ')) if user_age < 18: print('Sorry, access is restricted to adults only') else: print('Welcome to the site,', user_name, '!') input('Press Enter to go to the menu') print('Welcome to the menu') input('Press Enter to exit') input('Press Enter to exit') If the user enters an acceptable age, they will see the message inside the else block. Otherwise, they will see only the if block message and the final exit prompt. The input() function is used four times in this program, and in the last two cases, it does not store any values but serves to move to the next part of the code or exit the program. input() in the Python Interpreter The above example is a complete program, but you can also execute it line by line in the Python interpreter. However, in this case, you must enter data immediately to continue: >>> user_name = input('Enter your name: ') Enter your name: Jamie >>> user_age = int(input('How old are you? ')) How old are you? 18 The code will still execute, and values will be stored in variables. This method allows testing specific code blocks. However, keep in mind that values are retained only until you exit the interactive mode. It is recommended to save your code in a .py file. Input Conversion Methods: int(), float(), split() Sometimes, we need to convert user input into a specific data type, such as an integer, a floating-point number, or a list. Integer conversion (int()) We've already seen this in a previous example: user_age = int(input('How old are you? ')) The int() function converts input into an integer, allowing Python to process it as a numeric type. By default, numbers entered by users are treated as strings, so Python requires explicit conversion. A more detailed approach would be: user_age = input('How old are you? ') user_age = int(user_age) The first method is shorter and more convenient, but the second method is useful for understanding function behavior. Floating-point conversion (float()) To convert user input into a floating-point number, use float(): height = float(input('Enter your height (e.g., 1.72): ')) weight = float(input('Enter your weight (e.g., 80.3): ')) Or using a more detailed approach: height = input('Enter your height (e.g., 1.72): ') height = float(height) weight = input('Enter your weight (e.g., 80.3): ') weight = float(weight) Now, the program can perform calculations with floating-point numbers. Converting Input into a List (split()) The split() method converts input text into a list of words: animals = input('Enter your favorite animals separated by spaces: ').split() print('Here they are as a list:', animals) Example output: Enter your favorite animals separated by spaces: cat dog rabbit fox bear Here they are as a list: ['cat', 'dog', 'rabbit', 'fox', 'bear'] Handling Input Errors Users often make mistakes while entering data or may intentionally enter incorrect characters. In such cases, incorrect input can cause the program to crash: >>> height = float(input('Enter your height (e.g., 1.72): ')) Enter your height (e.g., 1.72): 1m72 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> height = float(input('Enter your height (e.g., 1.72): ')) ValueError: could not convert string to float: '1m72' The error message indicates that Python cannot convert the string into a float. To prevent such crashes, we use the try-except block: try: height = float(input('Enter your height (e.g., 1.72): ')) except ValueError: height = float(input('Please enter your height in the correct format: ')) We can also modify our initial age-input program to be more robust: try: user_age = int(input('How old are you? ')) except ValueError: user_age = int(input('Please enter a number: ')) However, the program will still crash if the user enters incorrect data again. To make it more resilient, we can use a while loop: while True: try: height = float(input('Enter your height (e.g., 1.72): ')) break except ValueError: print('Let’s try again.') continue print('Thank you!') Here, we use a while loop with break and continue. The program works as follows: If the input is correct, the loop breaks, and the program proceeds to the final message: print('Thank you!'). If the program cannot convert input to a float, it catches an exception (ValueError) and displays the message "Let’s try again."  The continue statement prevents the program from crashing and loops back to request input again. Now, the user must enter valid data before proceeding. Here is the complete code for a more resilient program: user_name = input('Enter your name: ') while True: try: user_age = int(input('How old are you? ')) break except ValueError: print('Are you sure?') continue if user_age < 18: print('Sorry, access is restricted to adults only') else: print('Welcome to the site,', user_name, '!') input('Press Enter to go to the menu') print('Welcome to the menu') input('Press Enter to exit') This program still allows unrealistic inputs (e.g., 3 meters tall or 300 years old). To enforce realistic values, additional range checks would be needed, but that is beyond the scope of this article. 
08 April 2025 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support