DEV Community

Russ Hensel
Russ Hensel

Posted on

Do not be Selfish: Use local variables to shadow your instance variables ( Python ).

Do not be Selfish: use local variables to shadow your instance variables ( Python ).

The following applies in many cases with objects. In this I will focus on a particular case: working with SQL in QT, a view and a model. A single window might have 2 models and 2 views. Setup code ( with some details left out ) might be something like this:

  • code with instance variables

    # the model 1
    self.model_1 = QSqlTableModel( ... )
    self.model_1.setTable( 'table_1')
    
    # the view 1
    self.view_1 = QTableView( )
    self.view_1.setModel( self.model_1  )
    self.view_1.hideColumn( 0 )
    self.view_1.setSelectionBehavior( QTableView.SelectRows )
    self.view_1.view.setSortingEnabled( True )
    
    # the model 2
    self.model_2 = QSqlTableModel( ... )
    self.model_2.setTable( 'table_2')
    
    # the view 2 -- with a mistake
    self.view_2 = QTableView( )
    self.view_2.setModel( self.model_1  )
    self.view_2.hideColumn( 3 )
    self.view_2.setSelectionBehavior( QTableView.SelectRows )
    self.view_2.setSortingEnabled( False )
    
  • less selfish code that shadows your instance variables but does exactly the same thing:

    # the model 1
    self.model_1 = QSqlTableModel( ... )
    self.model_1 = model
    
    model.setTable( 'table_1')
    
    # the view 1
    view = QTableView( )
    self.view_1  = view
    view.setModel( self.model_1  )
    view.hideColumn( 0 )
    view.setSelectionBehavior( QTableView.SelectRows )
    view.setSortingEnabled( True )
    
    # the model 2
    model = QSqlTableModel( ... )
    self.model_2 = model
    model.setTable( 'table_2')
    
    # the view 2 -- with a mistake corrected
    view = QTableView( )
    self.view_2 = view
    view.setModel( model  )
    view.hideColumn( 3 )
    view.setSelectionBehavior( QTableView.SelectRows )
    view.setSortingEnabled( False )
    

So what do I see that is different, and why do I like it:

  • self.model_1 mostly becomes model and self.view_1 mostly becomes view. And so on. ( in this case the shadowing is not exact it would be with self.model…. )

  • I have added 4 lines of code to the self.model_1….. but I have saved many characters of text.

  • Because of the local variables I can copy and paste the code to other places with many fewer changes.

  • My experiments show that using local variables like this is actually faster than instance variables.

  • If you mistype a local variable that is undefined your IDE will flag it as an error, this does not happen with instance variables because they can be defined very dynamically.

  • Is this faster coding, with faster running, and fewer bugs?

So what do you think:

worth a try?
useless?
obvious?
Enter fullscreen mode Exit fullscreen mode

Top comments (0)