Skip to content

Switch from singleton pattern to dependency injection #4149

Description

@codefiles

Singleton pattern

config.py

from pathlib import Path

class Config:
    def __init__(self, path, value):
        self.path = path
        self.value = value

config = Config(Path('/mnt'), 42)

general.py

from config import config

def use_config():
    content = (config.path / 'file').read_text()
    ...

main.py

from config import config
from general import use_config

def main():
    use_config()
    print(f'config: {config.path}, {config.value}')

if name == '__main__':
    main()

Dependency injection

config.py

class Config:
    def __init__(self, path, value):
        self.path = path
        self.value = value

general.py

def use_config(config):
    content = (config.path / 'file').read_text()
    ...

main.py

from pathlib import Path

from config import Config
from general import use_config

def main():
    config = Config(Path('/mnt'), 42)
    use_config(config)
    print(f'config: {config.path}, {config.value}')

if name == '__main__':
    main()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions