#๐Ÿ”’ How to create static class?

31 messages ยท Page 1 of 1 (latest)

sweet cobalt
#
class AssetStore(dict):
    def __init__(self, size):
        super().__init__()
        self.size = size
        self.load_assets()

    def load_assets(self):
        spritesheet_list = spritesheets.Spritesheets("assets/spritesheets")
        for asset_type, asset_dict in spritesheet_list.sheets.items():
            for asset_name, asset_data in asset_dict.items():
                asset_spritesheet = asset_data.get("spritesheet")
                if asset_spritesheet:
                    if asset_type not in self:
                        self[asset_type] = {}
                    new_asset = Asset(
                        asset_type,
                        asset_name,
                        animation=AnimationComponent(
                            asset_spritesheet.get_sprites(self.size, self.size),
                            asset_type,
                            asset_spritesheet.time_per_frame,
                        )
                    )
                    self[asset_type][asset_name] = new_asset
         
        for root, _, files in os.walk("assets/static"):
            for file in files:
                if file.split(".")[-1] == "png":
                    path_tokens = root.split("/")
                    asset_type = path_tokens[-2]
                    asset_name = path_tokens[-1]
                    if asset_type not in self:
                        self[asset_type] = {}
                    map = pygame.image.load(os.path.join(root, file)).convert_alpha()
                    new_asset = Asset(asset_type, asset_name, image=map)
                    self[asset_type][asset_name] = new_asset

    def __getitem__(self, key):
        return super().__getitem__(key)

I want this class to be accessed like an object without having to explicitly instantiate it. I want to be able to import it and use it like: AssetStore["some_asset"] without needed to (re)initialize the object explicitly. Is this possible? Bad practice? Thanks

lean ospreyBOT
#

@sweet cobalt

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

steel lintel
#

why not instantiate it?

sweet cobalt
#

idk it makes sense to me to not have to since it represents like a global store of all the assets

#

but maybe not

steel lintel
#
# my_module.py
class _AssetStore(dict):
    def __init__(self):
        # do initialization

AssetStore = _AssetStore(file_or_whatever)
from my_module import AssetStore
#

you could do something like that

sweet cobalt
#

oh i didnt know u could do that

#

so ur instantiating it once within its own module

#

and its accessible to all other modules that import that object?

steel lintel
#

when you import from a module all it's doing is (checking whether the module's already been imported) running the module and then giving you access to any names defined in it

sweet cobalt
#

oh interesting

#

yeah i was learning about singletons and thought I would have to use that instead

#

but this seems a lot simpler

steel lintel
#

this would still be considered a singleton pattern, as _AssetStore would be intended to only have 1 instance

sweet cobalt
#

and the underscore isnt any thing special right?

sweet cobalt
#

using like metaclasses or something

steel lintel
#

technically names with a leading underscore aren't imported when you do

from my_module import *
```but I was just using it to avoid giving the class and instance the same name
sweet cobalt
#

oh gotcha

#

one more thing, do you think this is bad practice

#

i heard singletons arent ideal because it leads to hidden dependencies

#

i suppose the alternative would be to pass in an AssetStore object to every class that needs it, but it felt a bit weird doing that

#

but maybe that is the best solution?

steel lintel
#

personally I think it's fine

#

although probably better to run your initialization code to create a normal dict, and then import that

sweet cobalt
#

yeah fair, was considering doing that as well

#

anyways thanks again

lean ospreyBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

๐Ÿ”’ How to create static class?