1

I am aware that circular dependencies is generally discouraged – yet, in C# and TypeScript I've sometimes found them useful. It might be my lack of experience with python, or maybe I'm thinking the wrong way or missing the right words to google for. How would I solve the following?

I'm trying to create a class that handles requests, and each of these handling events is accompanied by a context. So, I want to create the handler class, and the context class - but they are dependent, and the linter gives me problems on line 2, saying that HandlerService is not defined.

Example (dummy):

class HandlerContext:
    def __init__(self, service : HandlerService, uuid : str):
        self.service = service
        self.uuid = uuid

class HandlerService:
    def handle_request(self, context : HandlerContext, data : object):
        # do things ...
        pass
knut
  • 689
  • 5
  • 13

1 Answers1

4

You can use forward references, i.e. use service: "HandlerService" instead of service: HandlerService.

Note that in future python versions, this will become obsolete, as the annotation evaluation order will not be done at function definition time, but after all of them have been defined. You can start using this behavior with a from __future__ import annotations import in python 3.7, and later. See PEP563 for details.

RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
  • Thank you very much. Forward references seem to work well, and I get tooling in vscode with it. The import from futures does not do this however. Thanks again. – knut Dec 25 '18 at 18:28
  • 1
    Yes, the future import might not be implemented to work properly in your IDE. (Also make sure that you are on at least 3.7 if you want to try it) – RunOrVeith Dec 25 '18 at 18:31