Advanced Python Concepts Interview Questions
Comprehensive advanced python concepts interview questions and answers for Python. Prepare for your next job interview with expert guidance.
Questions Overview
1. What are metaclasses in Python and when should they be used?
Advanced2. How do descriptors work and what are their use cases?
Advanced3. What is the difference between __new__ and __init__?
Advanced4. How does Python's garbage collection work with reference counting and cycle detection?
Advanced5. What are abstract base classes and how do they differ from interfaces?
Advanced6. How do you implement custom context managers?
Advanced7. What are the advanced features of Python generators?
Advanced8. How do you implement custom attribute access?
Advanced9. What is method resolution order (MRO) and how does it work?
Advanced10. How do you implement custom iteration protocols?
Advanced11. What are slots and when should they be used?
Advanced12. How do you implement custom comparison methods?
Advanced13. What is the difference between bound and unbound methods?
Advanced14. How do you implement custom pickling behavior?
Advanced15. What are type hints and how do they enhance code?
Advanced16. How do you implement custom container types?
Advanced17. What are class decorators and how do they differ from function decorators?
Advanced18. How do you implement custom exception classes?
Advanced19. What are protocols in Python and how do they work?
Advanced20. How do you optimize memory usage in Python?
Advanced21. What are assignment expressions (walrus operator) and their use cases?
Advanced22. How do you implement custom number types?
Advanced23. What are generics in Python and how are they used?
Advanced24. How do you implement lazy property evaluation?
Advanced25. What are dataclasses and their advanced features?
Advanced26. How do you implement custom function and method wrappers?
Advanced27. What are async and await magic methods?
Advanced28. How do you implement custom attribute descriptors?
Advanced29. What are the advanced features of Python's memory model?
Advanced1. What are metaclasses in Python and when should they be used?
AdvancedMetaclasses are classes for classes, allowing customization of class creation. Used for API enforcement, attribute validation, class registration, abstract base classes. Created using type or custom metaclass. Example: class MyMetaclass(type): def __new__(cls, name, bases, attrs). Consider complexity trade-offs.
2. How do descriptors work and what are their use cases?
AdvancedDescriptors define __get__, __set__, __delete__ methods to customize attribute access. Used in properties, methods, class attributes. Enable managed attributes, validation, computed values. Example: property implementation using descriptors. Consider performance implications.
3. What is the difference between __new__ and __init__?
Advanced__new__ handles object creation (called before __init__), returns instance. __init__ initializes instance (called after __new__). __new__ used for immutable types, singletons, metaclasses. __init__ can't return value. Consider inheritance implications.
4. How does Python's garbage collection work with reference counting and cycle detection?
AdvancedUses reference counting for basic GC, generational GC for cycles. Reference count tracks object references, frees when zero. Cycle detector identifies and collects unreachable reference cycles. Consider memory management, performance implications.
5. What are abstract base classes and how do they differ from interfaces?
AdvancedABCs define interface through @abstractmethod, can include implementation. Created using abc.ABC. Enforce interface implementation, provide default methods. Unlike Java interfaces, can have implementation. Consider multiple inheritance implications.
6. How do you implement custom context managers?
AdvancedImplement __enter__ and __exit__ methods, or use contextlib.contextmanager decorator. Handle resource acquisition/release, exception handling. Consider cleanup guarantees. Example: file handling, database connections.
7. What are the advanced features of Python generators?
Advancedsend() method for two-way communication, throw() for exception injection, close() for generator cleanup. Generator delegation using yield from. Consider coroutine behavior, exception handling. Implement proper cleanup.
8. How do you implement custom attribute access?
AdvancedUse __getattr__, __setattr__, __getattribute__, __delattr__. Handle attribute lookup, modification, deletion. Consider infinite recursion, performance. Implement proper attribute management. Handle special cases.
9. What is method resolution order (MRO) and how does it work?
AdvancedMRO determines method lookup order in inheritance. Uses C3 linearization algorithm. Accessible via __mro__ attribute. Handles multiple inheritance, method overriding. Consider inheritance complexity, diamond problem.
10. How do you implement custom iteration protocols?
AdvancedImplement __iter__ and __next__ methods for iteration. Consider StopIteration handling. Implement proper cleanup. Handle resource management. Consider memory efficiency. Example: custom sequence types.
11. What are slots and when should they be used?
Advanced__slots__ restricts instance attributes, reduces memory usage. Faster attribute access, prevents dynamic attribute addition. Consider inheritance implications, flexibility trade-offs. Use for memory-critical applications.
12. How do you implement custom comparison methods?
AdvancedImplement rich comparison methods (__eq__, __lt__, etc.). Use @functools.total_ordering for complete ordering. Consider type checking, reflexivity, transitivity. Handle edge cases. Implement proper comparison logic.
13. What is the difference between bound and unbound methods?
AdvancedBound methods are instance-specific, include self parameter automatically. Unbound methods are class-level, require explicit instance. Consider method types, descriptor protocol. Handle method binding properly.
14. How do you implement custom pickling behavior?
AdvancedImplement __getstate__ and __setstate__ for custom serialization. Handle complex objects, circular references. Consider security implications. Implement proper state management. Handle version compatibility.
15. What are type hints and how do they enhance code?
AdvancedType hints provide static typing information. Used by type checkers (mypy), IDE support. Not enforced at runtime by default. Enhance code readability, maintainability. Consider performance impact, compatibility.
16. How do you implement custom container types?
AdvancedImplement container protocol methods (__len__, __getitem__, etc.). Consider sequence/mapping behavior. Handle iteration, containment checks. Implement proper indexing. Consider memory management.
17. What are class decorators and how do they differ from function decorators?
AdvancedClass decorators modify/enhance class definitions. Applied using @decorator syntax above class. Can modify class attributes, methods, add functionality. Consider inheritance implications. Handle class modification properly.
18. How do you implement custom exception classes?
AdvancedInherit from appropriate exception base class. Implement proper initialization, custom attributes. Consider exception hierarchy. Handle error messages, context. Implement proper cleanup. Document exception conditions.
19. What are protocols in Python and how do they work?
AdvancedProtocols define interface behavior without inheritance. Use typing.Protocol for static typing. Support structural subtyping. Consider duck typing implications. Implement protocol compatibility.
20. How do you optimize memory usage in Python?
AdvancedUse __slots__, proper data structures, generators. Consider memory profiling, garbage collection. Handle large datasets efficiently. Implement proper cleanup. Monitor memory usage. Consider caching strategies.
21. What are assignment expressions (walrus operator) and their use cases?
AdvancedAssignment expressions (:=) assign and return value in single expression. Used in while loops, if statements, list comprehensions. Enhances code readability, reduces redundancy. Consider proper usage contexts.
22. How do you implement custom number types?
AdvancedImplement numeric protocol methods (__add__, __mul__, etc.). Handle reverse operations (__radd__, etc.). Consider type coercion, precision. Implement proper arithmetic behavior. Handle special cases.
23. What are generics in Python and how are they used?
AdvancedGenerics provide type hints for collections/classes. Use typing.Generic, TypeVar. Support parametric polymorphism. Consider type checking implications. Implement proper type constraints. Handle type variables.
24. How do you implement lazy property evaluation?
AdvancedUse @property with caching, implement custom descriptors. Consider computation cost, memory usage. Handle invalidation properly. Implement thread safety. Consider cache management.
25. What are dataclasses and their advanced features?
Advanced@dataclass decorator provides automatic __init__, __repr__, etc. Support inheritance, frozen instances, default values. Consider field options, ordering. Implement custom initialization. Handle field dependencies.
26. How do you implement custom function and method wrappers?
AdvancedUse decorator pattern, functools.wraps for metadata preservation. Handle argument passing, return values. Consider function attributes. Implement proper wrapping. Handle special methods.
27. What are async and await magic methods?
Advanced__aiter__, __anext__, __aenter__, __aexit__ for async operations. Support async context managers, iterators. Handle coroutine behavior. Implement proper cleanup. Consider async patterns.
28. How do you implement custom attribute descriptors?
AdvancedCreate descriptor classes with __get__, __set__, __delete__. Handle attribute access, modification. Consider validation, computation. Implement proper state management. Handle inheritance.
29. What are the advanced features of Python's memory model?
AdvancedUnderstand object internals, reference counting, memory allocation. Handle weak references, object lifecycle. Consider memory sharing, copy semantics. Implement proper memory management. Handle circular references.