Skip to content

Added type hints to dependency injection pattern #328

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 18 additions & 12 deletions patterns/dependency_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,30 @@ def get_current_time_as_html_fragment(self):
"""

import datetime
from typing import Callable


class ConstructorInjection:

def __init__(self, time_provider):
def __init__(self, time_provider: Callable) -> None:
self.time_provider = time_provider

def get_current_time_as_html_fragment(self):
def get_current_time_as_html_fragment(self) -> str:
current_time = self.time_provider()
current_time_as_html_fragment = "<span class=\"tinyBoldText\">{}</span>".format(current_time)
current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format(
current_time
)
return current_time_as_html_fragment


class ParameterInjection:

def __init__(self):
def __init__(self) -> None:
pass

def get_current_time_as_html_fragment(self, time_provider):
def get_current_time_as_html_fragment(self, time_provider: Callable) -> str:
current_time = time_provider()
current_time_as_html_fragment = "<span class=\"tinyBoldText\">{}</span>".format(current_time)
current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format(
current_time
)
return current_time_as_html_fragment


Expand All @@ -54,16 +57,18 @@ class SetterInjection:
def __init__(self):
pass

def set_time_provider(self, time_provider):
def set_time_provider(self, time_provider: Callable):
self.time_provider = time_provider

def get_current_time_as_html_fragment(self):
current_time = self.time_provider()
current_time_as_html_fragment = "<span class=\"tinyBoldText\">{}</span>".format(current_time)
current_time_as_html_fragment = '<span class="tinyBoldText">{}</span>'.format(
current_time
)
return current_time_as_html_fragment


def production_code_time_provider():
def production_code_time_provider() -> str:
"""
Production code version of the time provider (just a wrapper for formatting
datetime for this example).
Expand All @@ -73,7 +78,7 @@ def production_code_time_provider():
return current_time_formatted


def midnight_time_provider():
def midnight_time_provider() -> str:
"""Hard-coded stub"""
return "24:01"

Expand Down Expand Up @@ -107,4 +112,5 @@ def main():

if __name__ == "__main__":
import doctest

doctest.testmod(optionflags=doctest.ELLIPSIS)