Skip to content

Latest commit

 

History

History
216 lines (156 loc) · 4.23 KB

File metadata and controls

216 lines (156 loc) · 4.23 KB

Python Special Variables

Core Special Variables (Most Common)

1. __name__

  • Represents the name of the module.
  • If the script is run directly, __name__ is set to "__main__".
  • If the script is imported, __name__ is set to the module’s name.
# example.py
if __name__ == "__main__":
    print("This script is run directly.")
else:
    print("This script is imported as a module.")

2. __file__

  • Contains the path of the script being executed.
print(__file__)  # Output: /path/to/script.py

3. __doc__

  • Stores the docstring of a module, class, or function.
def add(a, b):
    """This function returns the sum of two numbers."""
    return a + b

print(add.__doc__)  # Output: This function returns the sum of two numbers.

4. __dict__

  • Returns a dictionary representation of an object's attributes.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Luke", 25)
print(p.__dict__)  # Output: {'name': 'Luke', 'age': 25}

5. __builtins__

  • Contains built-in functions and exceptions.
print(dir(__builtins__))  # Lists all built-in functions

6. __annotations__

  • Stores type hints for functions.
def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet.__annotations__)  # Output: {'name': <class 'str'>, 'return': <class 'str'>}

7. __slots__

  • Optimizes memory usage by restricting dynamic attribute creation.
class Student:
    __slots__ = ['name', 'age']  # Only these attributes can be assigned

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

s = Student("John", 22)
# s.grade = "A"  # This will raise an AttributeError

8. __package__

  • Indicates the package a module belongs to.
print(__package__)  # Output: None (if run directly)

9. __cached__

  • Holds the path to the compiled .pyc file of the module.
import os
print(os.__cached__)  # Example Output: '/usr/lib/python3.10/__pycache__/os.cpython-310.pyc'

10. __all__

  • Defines a list of public objects for from module import *.
# mymodule.py
__all__ = ['func1', 'func2']

def func1():
    pass

def func2():
    pass

def func3():  # Won't be imported with `from mymodule import *`
    pass

Advanced Special Variables

11. __import__

  • A built-in function used to import modules dynamically.
math_module = __import__('math')
print(math_module.sqrt(16))  # Output: 4.0

12. __debug__

  • A boolean variable that is True unless Python is started with -O (optimize).
print(__debug__)  # Output: True

if __debug__:
    print("Debugging mode is on.")

13. __loader__

  • Stores the loader object responsible for importing a module.
import sys
print(sys.__loader__)  # Output: <class '_frozen_importlib.BuiltinImporter'>

14. __spec__

  • Provides details about the module’s import specification.
import sys
print(sys.__spec__)  # Shows metadata about the sys module

15. __bases__

  • Returns a tuple of base classes.
class A:
    pass

class B(A):
    pass

print(B.__bases__)  # Output: (<class '__main__.A'>,)

16. __mro__ (Method Resolution Order)

  • Shows the method resolution order for multiple inheritance.
class A: pass
class B(A): pass
class C(B): pass

print(C.__mro__)  
# Output: (<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)

17. __subclasses__()

  • Returns a list of subclasses of a given class.
print(int.__subclasses__())  # Lists all classes that inherit from int

Class & Object-Specific Special Variables

18. __class__

  • Returns the class of an instance.
x = 10
print(x.__class__)  # Output: <class 'int'>

19. __module__

  • Returns the module in which a class was defined.
class MyClass:
    pass

print(MyClass.__module__)  # Output: '__main__'

20. __weakref__

  • Used for managing weak references to objects.
import weakref

class Example:
    pass

obj = Example()
weak = weakref.ref(obj)
print(weak)  # Output: <weakref at 0x...; to 'Example' at 0x...>