Returns a global instance of this class. This method create a new instance if none have previously been created and returns a previously created instance is one already exists. The arguments and keyword arguments passed to this method are passed on to the :meth:`__i
(cls: type[CT], *args: t.Any, **kwargs: t.Any)
| 552 | |
| 553 | @classmethod |
| 554 | def instance(cls: type[CT], *args: t.Any, **kwargs: t.Any) -> CT: |
| 555 | """Returns a global instance of this class. |
| 556 | |
| 557 | This method create a new instance if none have previously been created |
| 558 | and returns a previously created instance is one already exists. |
| 559 | |
| 560 | The arguments and keyword arguments passed to this method are passed |
| 561 | on to the :meth:`__init__` method of the class upon instantiation. |
| 562 | |
| 563 | Examples |
| 564 | -------- |
| 565 | Create a singleton class using instance, and retrieve it:: |
| 566 | |
| 567 | >>> from traitlets.config.configurable import SingletonConfigurable |
| 568 | >>> class Foo(SingletonConfigurable): pass |
| 569 | >>> foo = Foo.instance() |
| 570 | >>> foo == Foo.instance() |
| 571 | True |
| 572 | |
| 573 | Create a subclass that is retrieved using the base class instance:: |
| 574 | |
| 575 | >>> class Bar(SingletonConfigurable): pass |
| 576 | >>> class Bam(Bar): pass |
| 577 | >>> bam = Bam.instance() |
| 578 | >>> bam == Bar.instance() |
| 579 | True |
| 580 | """ |
| 581 | # Create and save the instance |
| 582 | if cls._instance is None: |
| 583 | inst = cls(*args, **kwargs) |
| 584 | # Now make sure that the instance will also be returned by |
| 585 | # parent classes' _instance attribute. |
| 586 | for subclass in cls._walk_mro(): |
| 587 | subclass._instance = inst |
| 588 | |
| 589 | if isinstance(cls._instance, cls): |
| 590 | return cls._instance |
| 591 | else: |
| 592 | raise MultipleInstanceError( |
| 593 | f"An incompatible sibling of '{cls.__name__}' is already instantiated" |
| 594 | f" as singleton: {type(cls._instance).__name__}" |
| 595 | ) |
| 596 | |
| 597 | @classmethod |
| 598 | def initialized(cls) -> bool: |