Sobes.tech
Middle

What is reflection in the context of Python?

sobes.tech AI

Answer from AI

The ability of a program to explore and modify its own structure and behavior at runtime. Allows working with objects, types, functions, and modules whose names or structures are unknown prior to code execution.

Main features:

  • Getting information about type/object:
    • type() - get the type of an object.
    • isinstance() - check if an object is an instance of a class or subclass.
    • issubclass() - check if one class is a subclass of another.
  • Access to attributes:
    • getattr(obj, name[, default]) - get the value of an attribute.
    • setattr(obj, name, value) - set the value of an attribute.
    • hasattr(obj, name) - check if an attribute exists.
    • delattr(obj, name) - delete an attribute.
  • Access to documentation:
    • help() - interactive help.
    • __doc__ - access to the object's docstring.
  • Executing code:
    • eval(expression[, globals[, locals]]) - execute a string as a Python expression.
    • exec(object[, globals[, locals]]) - execute a string or code object.
  • Exploring namespace:
    • dir([object]) - list of names in the current namespace or attributes of an object.
    • globals() - dictionary of global variables in the current module.
    • locals() - dictionary of local variables in the current function or module.

Examples of usage:

class MyClass:
    def __init__(self, value):
        self.value = value

    def my_method(self):
        return self.value * 2

obj = MyClass(10)

# Getting type
print(type(obj)) # <class '__main__.MyClass'>

# Checking instance
print(isinstance(obj, MyClass)) # True

# Getting attribute by name
attr_name = "value"
print(getattr(obj, attr_name)) # 10

# Calling method by name
method_name = "my_method"
method = getattr(obj, method_name)
print(method()) # 20

# Setting a new attribute
setattr(obj, "new_attr", "hello")
print(obj.new_attr) # hello

# Executing code from string
code_string = "print('Executing code from string')"
exec(code_string) # Executing code from string

Table of main reflection functions:

Function Description
type() Get the type of an object
isinstance() Check if an object is an instance of a class
issubclass() Check if a class is a subclass of another
getattr() Get an attribute
setattr() Set an attribute
hasattr() Check if an attribute exists
delattr() Delete an attribute
help() Interactive help
__doc__ Access to the object's docstring
eval() Execute a string as an expression
exec() Execute a string or code object
dir() List of names in the namespace or attributes
globals() Dictionary of global variables
locals() Dictionary of local variables

Used in metaprogramming, debugging, serialization/deserialization, plugin architecture. Use with caution, as it can complicate code understanding and potentially create security issues (eval/exec).