How to dynamically load a Python class
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Dynamically loading a Python class means resolving the module and class name at runtime instead of importing them statically at the top of the file. This is useful for plugin systems, configurable backends, and factory code, but it should be done carefully because runtime loading moves errors from import time to execution time.
The Basic Pattern
The standard tool is importlib.import_module, followed by getattr to retrieve the class from the module.
This pattern separates the two steps clearly:
- import the module,
- fetch the named class from that module.
That is usually all you need for straightforward dynamic loading.
Loading from a Dotted Path
A common convenience is to accept one string such as package.module.ClassName and split it into the module part and the class part.
This is useful in configuration-driven systems where a JSON or YAML setting names the implementation to load.
Instantiate Only After Validation
Dynamic loading becomes safer if you validate what you loaded before instantiating it. For example, you may want to ensure the loaded object is actually a class or inherits from a required base type.
That kind of check prevents configuration mistakes from turning into stranger runtime failures later.
Handle Errors Explicitly
Dynamic imports fail in predictable ways:
- '
ModuleNotFoundErrorif the module does not exist,' - '
AttributeErrorif the class name is wrong,' - '
TypeErroror custom validation failures if the loaded object is not what you expect.'
A small wrapper can turn those into clearer application errors.
That makes troubleshooting much easier than letting a deep import stack trace leak into unrelated application logic.
Security and Design Considerations
Dynamic loading should not be treated as a free-form input feature for arbitrary user strings. If the module path comes from an untrusted source, you are effectively letting external input influence what code gets imported.
In real systems, prefer one of these patterns:
- load only from a fixed package,
- validate against an allowlist,
- or map friendly configuration names to known implementation paths.
The flexibility is useful, but unrestricted dynamic import is rarely the safest design.
Common Pitfalls
- Using
__import__directly whenimportlib.import_moduleis clearer. - Forgetting that module import and class lookup are separate steps.
- Loading the class successfully but not validating whether it matches the expected interface or base class.
- Treating untrusted strings as safe import paths.
- Making debugging harder by scattering dynamic import logic instead of wrapping it in one helper function.
Summary
- Dynamic class loading in Python is usually done with
importlib.import_moduleandgetattr. - A dotted path such as
package.module.ClassNameis a convenient input format. - Validate the loaded class before instantiating it if the application expects a specific interface.
- Handle module and attribute errors explicitly to keep failures understandable.
- Use dynamic loading carefully when configuration or external input controls the import path.
Related reading
- How to efficiently compare two unordered lists not sets?
- How to efficiently compare two unordered lists not sets?
- How to empty a list?
- How to enable CORS in flask
- How to ensure task execution order per user using Celery, RabbitMQ and Django?
- How to erase the file contents of text file in Python?
- How to escape curly-brackets in f-strings?
- How to establish a connection to DynamoDB using python using boto3
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.