[Python] Best way of separating data from python code

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    If have a method that matches strings to regex patterns in a dictionary and returns corresponding value.

    # Module foo.py
    class bar:
    def __init__(self, patterns):
    self._patterns = patterns

    def baz(self, string)
    for pattern, value in self._patterns:
    # return value if string matches pattern


    # In another module
    patterns = {...}
    obj = foo.bar(patterns)


    I want a reusable dict of patterns. Does it make sense to move it to foo.py like

    # foo.py
    default_patterns = {...}

    class bar:
    ...

    # In another module
    obj = foo.bar(foo.default_patterns)


    Or should i use a json file? Something like

    with open(filename) as file:
    patterns = load(file)

    obj = foo.bar(pattenrs)


    In this case where do I keep this file? Also will it make sense to keep the path in the module as some PATTERN_FILENAME variable.

    Continue reading...

Compartilhe esta Página