Skip to main content

Been reading up on #Python lately. I know that classes in Python "doesn't support" private values, but could this functionality not be implemented with closures?

Edit: typo

Content warning: boring nerd stuff (example code)

Content warning: boring nerd stuff (example code)

This entry was edited (2 months ago)
something like this? Sure the class can save the value in a method and return that later, but then i get the same problem, anything can decide to patch this method instead.
Python class patching its own method to return a different result
class ClosureClass:
    def set_val(self, value):
        self.get_val = lambda: value

    def get_val(self):
        return "default value"

if __name__ == '__main__':
    cl = ClosureClass()
    cl.set_val("another value")


running this code displays
default value                                                                                                                                      
another value                                                                                                                                      
default value
@Gabriel Pettier That's even cleaner than what I'd conceptualized, yes.
well, it's not very clean, as self modifying code is not a good friend of code that is easy to reason about and maintain, and that will likely confuse type checkers and other tools. And it doesn't solve the problem, since i can totally do cl.get_val = lambda: "test" instead of calling cl.set_val("test").
@Gabriel Pettier That's true. It's not what I would consider to be a *good* idea. I was just reading in the docs where it said Python had *no way* of creating private variables, and I thought: Is that *really* true?

At the very least, it's fair to say that there is no official way.
Someone argued that Python is a language for adults and "private" variables are therefore not needed. There will always be ways to access them anyway but responsible programmers would just leave them alone.
@Maurice LéDuck I guess. I just hate polluting my namespaces unecessarily.
If the #Python rules and conventions of _ prefixes don't meet the needs for 'privacy', perhaps choose another tool from the tool-box instead of trying to hammer-in a screw?
@dn Not my project. I didn't pick the tool.

That said, it was more of a hypothetical question.

This website uses cookies. If you continue browsing this website, you agree to the usage of cookies.