[Python-de] Re: Code Style Review

[email protected]
Newsgroups gmane.comp.python.general.german
Message-ID <[email protected]>
Am 28.11.2022 21:52 schrieb Marc Haber:
> Das sehe ich mindestens teilweise anders. Wenn ich irgendwo explizit
> hinschreibe, dass eine Funktion eine globale Variable verwendet (wie
> z.B. das dictionary, in dem die Konfiguration drin steht) und der
> Linter das unkonditional anmeckert nur allein weil das Schlüsselwort
> benutzt wurde ergibt das für mich keinen Sinn

Auch wenn es radikal klingen mag; Es hat keinen Sinn "global" zu 
verwenden, auch wenn Python das im Sprachumfang hat. Ein "global" hat 
sehr viele Nebeneffekte und birgt potentielle Risiken, die den Gewinn 
nicht aufwiegen. Es gibt andere Lösungen.

> Gerade für die Konfiguration halte ich die globale Variable auch für
> den vernünftigen Weg, das wirklich überall bekannt zu machen.

Nein, ist es nicht. Das ist nur eine "Abkürzung". Besser wäre hier eine 
Art Singleton-Pattern anzuwenden.
Sagen wir deine Konfiguration ist in der Klasse "Config".

class Config:
     @classmethod
     def instance(cls):
         # Provide the instance if it exists
         if cls._instance:
             return cls._instance

         # But don't created implicit when needed.
         raise Exception(f'No instance of class "{cls}" exists. '
                         'Create an instance first.')

     def __init__(self):
         # Exception when an instance exists
         if __class__._instance:
             raise Exception(
                 f'Instance of class "{self.__class__.__name__}" still 
exists!'
                 f' Use "{self.__class__.__name__}.instance()" to access 
it.')

         # Remember the instance as the one and only singleton
         __class__._instance = self

Quelle: 
https://github.com/bit-team/backintime/blob/buhtz_config-singleton/common/config.py
_______________________________________________
python-de Mailingliste -- [email protected]
Zur Abmeldung von dieser Mailingliste senden Sie eine Nachricht an [email protected]
https://mail.python.org/mailman3/lists/python-de.python.org/
Mitgliedsadresse: [email protected]
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.