Skip to content

Special Syntax in Python

1. Keywords with __ (Double Underscore) in Python

Section titled “✅ 1. Keywords with __ (Double Underscore) in Python”

These are “Dunder” (Double Underscore) Methods & Variables, mainly used for special functions and attributes in Python.

Dunder NamePurpose
__init__Constructor method in classes
__str__String representation (str(obj))
__repr__Debug representation (repr(obj))
__name__Module name (__name__ == "__main__")
__call__Make an object callable (obj())
__len__Length of an object (len(obj))
__getitem__Indexing support (obj[key])
__setattr__Control setting attributes
__del__Destructor method
__new__Customize object creation
  • These are not “keywords”, but rather special names recognized by Python.

These are called “Decorators”, which modify functions or methods.

DecoratorPurpose
@decoratorDefines a decorator function
@classmethodDefines a class method
@staticmethodDefines a static method
@propertyDefines a getter property
@app.route()Flask route decorator (e.g., @app.route("/"))
@pytest.markPytest test marker
  • Decorators start with @ and modify functions/classes.

Python String Prefixes & Format Strings

Section titled “✅ Python String Prefixes & Format Strings”
PrefixMeaningExample
f"" or f'''Formatted String Literal (f-strings)name = "Gaurav"; print(f"Hello {name}")"Hello Gaurav"
r"" or r''Raw String (ignores escape sequences)print(r"C:\new\folder")"C:\new\folder"
b"" or b''Byte Stringb"hello"b'hello'
u""Unicode String (Python 2, redundant in Python 3)u"hello""hello"
""" or '''Multiline String"""Hello\nWorld""""Hello\nWorld"
% FormattingOld String Formatting"Hello %s" % "Gaurav"
.format()String format() method"Hello {}".format("Gaurav")
  • f""Best for dynamic formatting (faster & readable).
  • r""Best for regex or Windows paths (avoids \n issues).
  • b""For byte data, encoding purposes.
  • """ """For docstrings & multi-line text.