Modules
Simple IOC container.
Classes:
Container
MissingDependencyError
InvalidRegistrationError
InvalidForwardReferenceError
MissingDependencyException
InvalidRegistrationException
InvalidForwardReferenceException
Scope
Misc Variables:
empty
Container
¶
Provides dependency registration and resolution.
This is the main entrypoint of the Punq library. In normal scenarios users will only need to interact with this class.
Source code in punq/__init__.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 |
|
instantiate(service_key, **kwargs)
¶
Instantiate an unregistered service.
Source code in punq/__init__.py
register(service, factory=empty, instance=empty, scope=Scope.transient, **kwargs)
¶
Register a dependency into the container.
Each registration in Punq has a "service", which is the key used for resolving dependencies, and either an "instance" that implements the service or a "factory" that understands how to create an instance on demand.
Examples:
If we have an object that is expensive to construct, or that wraps a resouce that must not be shared, we might choose to use a singleton instance.
>>> class DataAccessLayer:
... pass
...
>>> class SqlAlchemyDataAccessLayer(DataAccessLayer):
... def __init__(self, engine: sqlalchemy.engine.Engine):
... pass
...
>>> dal = SqlAlchemyDataAccessLayer(sqlalchemy.create_engine("sqlite:///"))
>>> container.register(
... DataAccessLayer,
... instance=dal
... )
<punq.Container object at 0x...>
>>> assert container.resolve(DataAccessLayer) is dal
If we need to register a dependency, but we don't need to abstract it, we can register it as concrete.
>>> class FileReader:
... def read (self):
... # Assorted legerdemain and rigmarole
... pass
...
>>> container.register(FileReader)
<punq.Container object at 0x...>
>>> assert type(container.resolve(FileReader)) == FileReader
In this example, the EmailSender type is an abstract class and SmtpEmailSender is our concrete implementation.
>>> class EmailSender:
... def send(self, msg):
... pass
...
>>> class SmtpEmailSender (EmailSender):
... def send(self, msg):
... print("Sending message via smtp")
...
>>> container.register(EmailSender, SmtpEmailSender)
<punq.Container object at 0x...>
>>> instance = container.resolve(EmailSender)
>>> instance.send("beep")
Sending message via smtp
Source code in punq/__init__.py
resolve(service_key, **kwargs)
¶
Build and return an instance of a registered service.
resolve_all(service, **kwargs)
¶
Return all registrations for a given service.
Some patterns require us to use multiple implementations of an interface at the same time.
Examples:
In this example, we want to use multiple Authenticator instances to check a request.
>>> class Authenticator:
... def matches(self, req):
... return False
...
... def authenticate(self, req):
... return False
...
>>> class BasicAuthenticator(Authenticator):
... def matches(self, req):
... head = req.headers.get("Authorization", "")
... return head.startswith("Basic ")
...
>>> class TokenAuthenticator(Authenticator):
... def matches(self, req):
... head = req.headers.get("Authorization", "")
... return head.startswith("Bearer ")
...
>>> def authenticate_request(container, req):
... for authn in req.resolve_all(Authenticator):
... if authn.matches(req):
... return authn.authenticate(req)
Source code in punq/__init__.py
InvalidForwardReferenceError
¶
Bases: InvalidForwardReferenceException
Raised when a registered service has a forward reference that can't be resolved.
Examples:
In this example, we register a service with a string as a type annotation. When we try to inspect the constructor for the service we fail with an InvalidForwardReferenceError
>>> from dataclasses import dataclass
>>> from punq import Container
>>> @dataclass
... class Client:
... dep: 'Dependency'
>>> container = Container()
>>> container.register(Client)
Traceback (most recent call last):
...
punq.InvalidForwardReferenceError: name 'Dependency' is not defined
This error can be resolved by first registering a type with the name 'Dependency' in the container.
>>> class Dependency:
... pass
...
>>> container.register(Dependency)
<punq.Container object at 0x...>
>>> container.register(Client)
<punq.Container object at 0x...>
>>> container.resolve(Client)
Client(dep=<punq.Dependency object at 0x...>)
Alternatively, we can register a type using the literal key 'Dependency'.
>>> class AlternativeDependency:
... pass
...
>>> container = Container()
>>> container.register('Dependency', AlternativeDependency)
<punq.Container object at 0x...>
>>> container.register(Client)
<punq.Container object at 0x...>
>>> container.resolve(Client)
Client(dep=<punq.AlternativeDependency object at 0x...>)
Source code in punq/__init__.py
InvalidForwardReferenceException
¶
InvalidRegistrationError
¶
InvalidRegistrationException
¶
MissingDependencyError
¶
Bases: MissingDependencyException
Raised when a service, or one of its dependencies, is not registered.
Examples:
>>> import punq
>>> container = punq.Container()
>>> container.resolve("foo")
Traceback (most recent call last):
punq.MissingDependencyError: Failed to resolve implementation for foo
Source code in punq/__init__.py
MissingDependencyException
¶
Scope
¶
Bases: Enum
Controls the lifetime of resolved objects.
Attributes:
Name | Type | Description |
---|---|---|
transient |
create a fresh instance for each |
|
singleton |
re-use a single instance for every |