Editing Python Names

Jump to navigation Jump to search

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then save the changes below to finish undoing the edit.

Latest revision Your text
Line 4: Line 4:
 
The right answer is all the time, but in practice people go to more effort when they expect the program to be around for a longer time.  Also in practice programs tend to be around longer than you expect.  Try to develop good habits, it will pay off.
 
The right answer is all the time, but in practice people go to more effort when they expect the program to be around for a longer time.  Also in practice programs tend to be around longer than you expect.  Try to develop good habits, it will pay off.
 
= Short vs Long =
 
= Short vs Long =
Really short names are rarely good they just have too little meaning.  You should remember that a program is more often read than written ( only once not counting fix up ) so make it easy to read. That said names can get too long.  Over 12 characters?: take a second look.  Abbreviation are fine but should be consistent.  I use hi and lo for high and low, max and min for maximum and minimum.  But n for number? Too short, also may hide an important function n().
+
Really short names are rarely good they just have too little meaning.  You should remember that a program is more often read than written ( only once not counting fix up ) so make it easy to read. That said names can get too long.  Over 12 characters?: take a second look.  Abriviations are fine but should be consistent.  I use hi and lo for high and low, max and min for maximinum and minimum.  But n for number? Too short, also may hide an important function n().
  
Short vs long also applies to how long the variable will exist, or be in scope.  If the scope of a variable is short, it is easier to live with a short, and less clear, name.  I use ix for a index with short scope, if the scope is longer then I might use ix_toy if the index is indexing into a list of toys.
+
Short vs long also applies to how long the variable will exist, or be in scope.  If the scope of a variable is short, it is easier to live with a short, and less clear, name.
 
 
= Singular vs Plural =
 
 
 
Often I use a plural for a list, a list of toys might be toys, an element in it a toy ( or a_toy, or if indexing through the list ix_toy for the numerical index and i_toy for toys[ix_toy].
 
 
 
<pre>
 
    for ix_toy, i_toy enumerate( toys ):
 
            i_toy.my_index  = ix_toy      # not necessarily a useful example of code
 
</pre>
 
 
 
= Generic Variables =
 
 
 
Sometimes it is useful to use generic names rather than specific ones.  One use I often encounter is in constructing tkiner gui's.  Say I want a button, and want to configure it in some specific way:
 
 
 
<pre>
 
        a_button = Button( a_frame , width=10, height=2, text = "Edit Parms" )
 
        a_button.config( command = self.controller.os_open_parmfile )
 
        a_button.pack( side = LEFT )
 
</pre>
 
 
 
This is fine, but I often copy the code and use it for a different widiget ( many widgets use the same sorts of parameters and setup functions.  Then I may ue a more generic name.
 
 
 
<pre>
 
            # record checkbox
 
            cb_record_var    = IntVar()
 
            a_widget    = Checkbutton( a_frame, text="Record", variable=cb_record_var, width = 10, anchor="w" )
 
            a_widget.config( command = lambda ix = ix__smartplug_adapter: self.controller.cb_device_action( ix, "record" ) )
 
            a_widget.config( borderwidth = 5, relief = RAISED,  )
 
            a_widget.grid( row = lrow * rowspan, column = lcol, rowspan = 2, sticky=E + W + N + S )
 
            i_smartplug_adapter.gui_tk_record_checkbox_var  = cb_record_var
 
            lcol +=  1
 
 
 
    # time combobox
 
            times = ( "infinite", .1, .5, 1,  2, 3, 5, 10, 15, 20, 25, 30, 40, 50, 60  )   
 
            a_widget  =  ttk.Combobox( a_frame, values=times, state='readonly',  width = 10, ) 
 
            a_widget.current( 6 )    # set default value
 
            a_widget.grid( row = lrow * rowspan, column = lcol, rowspan = rowspan, sticky=E + W + N + S )
 
            i_smartplug_adapter.gui_tk_combo = a_widget
 
            lcol +=  1
 
</pre>
 
 
 
= Local Variables =
 
 
 
Local variables are fast, and may be useful as generic variables ( see above ).  But some times as for the combo box ( above ) you need a reference to be used later ( i_smartplug_adapter.gui_tk_combo = a_widget ).  But it is useful and ( I think faster and easier ) to use a more generic local variable for the set up and initial manipulations, and save the reference at the end ).
 
  
 
= Avoid Reserved Words =
 
= Avoid Reserved Words =
Line 56: Line 12:
 
Reserved words are words that are reserved for the language that you are not suppose to use, words like if, else, while, def.  Python will actually throw an syntax error in most cases if you use them.   
 
Reserved words are words that are reserved for the language that you are not suppose to use, words like if, else, while, def.  Python will actually throw an syntax error in most cases if you use them.   
  
There are even more words that you should treat as reserved words, that is do not use them.  These words are ones that other parts of the language may already be using. Suppose that you are doing some math.  Then you might suspect that words like sin, sine, min, max, random might already be in use.  Try to be a bit careful.  In some contexts both n and i are already defined ( i for the imaginary unit, n for a function that forces numerical evaluation )
+
There are even more words that you should treat as reserved words, that is do not use them.  These words are ones that other parts of the language may already be using. Suppose that you are doing some math.  Then you might suspect that words like sin, sine, min, max, random might already be in use.   
  
For words that are reserved, are already in use, or look as if they might be, I often prefix them with "a_".  So if I have a reference to a thread I will call it something like "a_thread".
+
Python can multi task with things called threads.  So if I am programming in this area and am tempted to use the word thread I will instead call it a_task, my_thread.  Try to be a bit careful. In some contexts both n and i are already defined ( i for the imaginary unit, n for a function that forces numerical evaluation )
  
 
= Break into Words =
 
= Break into Words =
  
If you use temp for temperature ( and beware some people use it for temporary ) then the high and low temperatures would be hi_temp and low_temp.  Another style is HiTemp and LoTemp.  The second is called camel case.
+
If you use temp for temperature ( and beware some people use it for temporary ) then the high and low temperaturs would be hi_temp and low_temp.  Another style is HiTemp and LoTemp.  The second is called camel case.
  
 
Most Python is written using underscores for variable name and functions, camel case is used for class names.  Again be consistent.
 
Most Python is written using underscores for variable name and functions, camel case is used for class names.  Again be consistent.
 
= Verbs and Nouns =
 
 
Most functions ( methods... ) do something.  So make them verbs or verb like.  Classes are typically more like things, so make them noun like. 
 
<pre>
 
      self.monitor_state  = 1                # noun
 
      plug_adapter        = PlugAdapter()    # noun
 
      def display_help():                    # verb like
 
</pre>
 
 
 
= Declare at top of Class =
 
 
Actually Python does not have declarations but for me this means do an assignment in __init__ or very nearby and comment the variables.  Sometimes this is a natural part of the initialization, other times it is not, perhaps because the value is not know yet.  In this case assign it to None.
 
 
<pre>
 
    self.live_graph_lines    = None      # lines on the graph, we keep for later updating
 
</pre>
 
= Variables =
 
 
Most programming languages have variables, and Python users often refer to variables, but actually, sort of, '''Python does not have variables''' it has '''names'''.  Is this a difference that makes a difference?  If I say:
 
 
<pre>
 
    self.monitor_state  = 1 
 
    # then....       
 
    self.monitor_state  = 2 
 
</pre>
 
 
Then self.monitor_state has changed or varied, so it must be a variable.  Yes and No.  self.monitor_state is a name and at one time it "pointed to" a value of 1 and later it  "pointed to" a value of 2.  A mutable object is in some ways more like a variable.  I will not say more here, but at some point you might want to investigate this issues because, sometimes, they make a difference.
 
You may find this useful: '''[https://www.youtube.com/watch?v=4MCT4WLf7Ac&__s=dibfsizig3wuxjywoekt (26) "Python Oddities Explained" - Trey Hunner (PyCon AU 2019) - YouTube ]''' and '''[https://treyhunner.com/python-oddities/#/3 Python Oddities Explained ]'''
 
 
= Class Instance Variables =
 
 
I try to name variables that refer to classes with names that reflect the class.  Since the class is in camel case and the instance variable uses underscores this is often simple
 
 
<pre>
 
      self.gui      = Gui()
 
      plug_adapter  = PlugAdapter()
 
</pre>
 
  
 
= Examples =
 
= Examples =

Please note that all contributions to OpenCircuits may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see OpenCircuits:Copyrights for details). Do not submit copyrighted work without permission!

Cancel Editing help (opens in new window)