Python Forum
Pythonic way to handle/spread alerts class in multiple modules
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pythonic way to handle/spread alerts class in multiple modules
#2
(Feb-05-2020, 01:15 PM)psolar Wrote: But when I import and instantiate the class, lists are empty.
It does work as intended for me.
class Borg:
    shared_state = {}

    def __init__(self):
        self.__dict__ = self.shared_state
        self.state = 'Init'
usage:
>>> from test11 import Borg
>>> borg1 = Borg()
>>> borg2 = Borg()
>>> borg1.state
'Init'
>>> borg2.state
'Init'
>>> borg1.state = 'test'
>>> borg1.state
'test'
>>> borg2.state
'test'
If done this way i would definitely make the variable name obvious that it is shared to avoid thinking it is an instance attribute independent from other instances.

I usually call Borg.shared_state directly when changing or referring to any class attribute. Im not sure which is more pythonic to be honest.
Recommended Tutorials:
Reply


Messages In This Thread
RE: Pythonic way to handle/spread alerts class in multiple modules - by metulburr - Feb-05-2020, 05:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Can I use logging in a class (without multiple messages) mevan 2 693 Oct-16-2023, 11:08 PM
Last Post: mevan
  What's the best way for multiple modules to handle database activity? SuchUmami 3 756 Jul-08-2023, 05:52 PM
Last Post: deanhystad
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 2,416 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  which is "better" (or more Pythonic)? Skaperen 2 2,125 Feb-01-2020, 03:10 PM
Last Post: Skaperen
  which is "better" (or more Pythonic)? Skaperen 7 3,354 Feb-01-2020, 03:51 AM
Last Post: Skaperen
  which is "better" (or more Pythonic)? Skaperen 8 3,510 Nov-16-2019, 06:46 PM
Last Post: Skaperen
  which is more Pythonic? Skaperen 5 2,972 Jul-16-2019, 01:00 AM
Last Post: Skaperen
  spread same class into separate files in python asheru93 3 5,658 Jun-19-2019, 02:06 PM
Last Post: ichabod801
  Giving class multiple arguments AndyArsalan 1 4,641 Oct-04-2018, 11:25 PM
Last Post: ODIS
  the best way to handle the class "value" Levitanus 1 2,107 Jul-22-2018, 08:30 PM
Last Post: Levitanus

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020