Search code examples
pythonfieldprivate

Strategy for Private Fields in Python


I have the following Python code, which I think emulates a "private" field in the sense that we create a variable that can only accessed by a getter and modified by a setter, not directly discovered.

class Foo:
  def __init__( self, value ):
    node = Node( value )
    self.get = lambda : node.get()
    self.set = lambda newValue : node.set( newValue )

class Node:
  def __init__( self, value ):
    self.value = value
  def set( self, value ):
    self.value = value
  def get( self ):
    return self.value

if __name__ == "__main__":
    f = Foo( 17 )
    print dir(f) #prints __doc__, __init__, __module__, get, set
    print f.get() #prints 17
    f.set(16)
    print f.get() #prints 16

Unlike Java, private fields aren't built into Python for various reasons that are discussed in other threads, but I'm wondering what the advantages/disadvantages of using this method of restricting variables are? Are there ways of accessing these "private" variables without using the getting/setting methods?

Obviously, the strategy could be extended well beyond getting and setting if we wanted to model Java private variables and functions, and I understand that this could make for some unwieldy code - let's say that we're not worried about elegance. Is there a name for this type of programming?


Solution

  • A determined user can still get around your defenses by doing

    f.get.__closure__[0].cell_contents.value
    f.get.__closure__[0].cell_contents.value = "some new value"
    

    The general disadvantage of programming this way is that all you do is create more work for yourself, and despite all that work you still can't ever really stop anyone from accessing the "private" data.