0

First of all I would like you to know that I read different topics about: cyclic import, cycling type hints and so on. According to this answer we can notice that:

States store a reference to the context object that contains them.

And I need exactly such solution. So I prepared two demo files, state.py:

from abc import ABC, abstractmethod


class State(ABC):

    @abstractmethod
    def set_screen_brightness(self, computer: Laptop) -> None:
        pass

class PowerSupplyOn(State):

    def set_screen_brightness(self, computer: Laptop) -> None:
        computer._set_max_brightness()

class PowerSupplyOff(State):

    def set_screen_brightness(self, computer: Laptop) -> None:
        computer._set_min_brightness()

and laptop.py:

from states import *


class Laptop:

    def __init__(self) -> None:
        self.state = PowerSupplyOn()
        self.adjust_brightness_screen()

    def adjust_brightness_screen(self) -> None:
        self.state.set_screen_brightness(self)

    def _set_max_brightness(self) -> None:
        print('Brightness level: 100%')

    def _set_min_brightness(self) -> None:
        print('Brightness level: 15%')

Going to the point - I stuck. Of course I can't import Laptop inside state.py (cyclic imports). On the other hand I need type hints. Alternatively, I can remove Laptop hints from method's headers (but I need them) or make them as strings, i.e. 'Laptop'. Or maybe I shouldn't pass back-reference to the context (Laptop class) at all?

How to deal with this issue?

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Benek
  • 91
  • 11
  • Do you absolutely need a reference to the context? I'm not sure the GoF definition has the cyclic link. See https://stackoverflow.com/a/30424503/1168342 for a diagram as well as some dynamics of state changes. – Fuhrmanator Jan 19 '20 at 04:52
  • Yes, because the Context inherits from another class and triggers some objects in independent processes which must be handled by the Context itself. I know that the GoF definition doesn't have the cyclic link, but it works, [see this topic](https://stackoverflow.com/a/54619178/3548713). – Benek Jan 19 '20 at 09:53

0 Answers0