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
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 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 |
|
child()
¶
Create a new container that inherits configuration from this one.
You may need to change dependencies for a particular scope of your system, for example, to override them in tests, or to add per-request data.
Punq supports "child" containers for this purpose.
Examples:
In this example, we want to register a per-request dependency into our child container. Each child will resolve its own instance of the RequestData. The order of registration is unimportant.
>>> class RequestHandler:
...
... def __init__(self, state: RequestData):
... self.state= state
...
... def handle(self) -> None:
... print(self.state)
...
>>> first_request_container = app_container.child()
>>> second_request_container = app_container.child()
>>> first_request_container.register(RequestData, instance=RequestData(123, True))
<punq.Container object at 0x...>
>>> second_request_container.register(RequestData, instance=RequestData(789, False))
<punq.Container object at 0x...>
>>> first_request_container.resolve(RequestHandler).handle()
RequestData(user_id=123, is_admin=True)
>>> second_request_container.resolve(RequestHandler).handle()
RequestData(user_id=789, is_admin=False)
Source code in punq/__init__.py
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
¶
RegistrationScope
¶
Simple chained dictionary[service, list[implementation]].
Source code in punq/__init__.py
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 |