Вопрос
Why does a custom nn.Module need super().__init__()? Separately, why is tags=[] as a default argument in Python dangerous?
Ответить самому
Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.
Короткий ответ
nn.Module.__init__ initializes internal registries for parameters, buffers and submodules. A mutable default list is shared across calls, so mutations leak between instances.
Полный разбор
A custom PyTorch module should call super().__init__() before assigning submodules. nn.Module.__init__ creates internal dictionaries and hooks used to register parameters, buffers and child modules. Without it, methods may exist through inheritance, but assigning Linear layers and later calling parameters(), state_dict(), train(), eval() or to(device) can break or behave incorrectly.
The Python default argument issue is separate. Default values are evaluated once when the function is defined, not each time it is called. If tags=[] is used and one call mutates that list, later calls without tags see the same mutated object. The usual pattern is tags: list[str] | None = None, then inside the function create a new empty list when tags is None.
The common theme is object lifecycle: initialization matters for framework objects, and defaults must not hide shared mutable state.
Теория
PyTorch modules rely on parent-class initialization; Python default values are persistent objects.
Типичные ошибки
- Think inheritance alone initializes nn.Module internals.
- Use [] or {} as default arguments.
- Use `tags or []` when an explicitly empty list has semantic meaning.
Как отвечать на собеседовании
- Mention parameter registration for super().__init__.
- Give a tiny example of two instances sharing the same default list.