DEV Community


Discussion on: [Challenge] log("this") or log("this").withData({})

idanarye profile image
Idan Arye

This is possible in Python by utilizing the destructor and relying on the fact that Python uses reference counting as its first GC tier:

class log:  # yes this is a class but you can just use it like a function
    def __init__(self, text):
        self.text = text
        self.print_on_dtor = True

    def __del__(self):
        if self.print_on_dtor:
            self.print_on_dtor = False
            print('log:', self.text)

    def with_data(self, data):
        self.print_on_dtor = False
        print('withData:', self.text, data)

JS doesn't have destructors so you can't use that trick there. I'm also not sure if the GC is as predictable as Python's (and with all the various implementations I won't be surprised if it has different rules on different engines...)