#πŸ”’ If a `Callable` is set as an attribute of a class it is being treated as a method.

8 messages Β· Page 1 of 1 (latest)

ornate jasper
#

I'm working to extend some functionality of the SSG I maintain to be able to render arbitrary serializable objects as JSON, TOML, or other standardized formats.

class DataObject(BaseObject):
    """Class to store a data object"""
    data_object: Any = None  # The data object
    output_file: str | Path = Path('data_object.json')
    serializer: Callable = json.dumps
    serializer_args: dict | None = None

    def render(self, *args, **kwargs):
        """
        Renders the data_object to the file at output_file
        """
        path = Path(site.output_path) / Path(self.output_file)
        path.parent.mkdir(parents=True, exist_ok=True)

        serialized = self.serializer(self.data_object)

        path.write_text(serialized)

For some reason, self.serializer is being treated like a method of the class and I am getting:

  File "/Users/brass75/src/render-engine/src/render_engine/data_object.py", line 41, in render
    serialized = self.serializer(data_object)
TypeError: dumps() takes 1 positional argument but 2 were given

Does anyone know what I need to do to maintain this Callable attribute as a function, and not as a method of DataObject?

tough ermineBOT
#

@ornate jasper

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.

dense cape
#

Two things you might be able to do,
mark it as a staticmethod

serializer = staticmethod(json.dumps)

or assign it to the object during __init__

def __init__(self, ...):
    self.serializer = json.dumps
ornate jasper
#

Thank you.

#

Now I just need to get this into a format where I can actually use it for the app but I have where to start.

#

!close

tough ermineBOT
#
Python help channel closed with !close

This help channel has been closed. 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.