Python Names

From OpenCircuits
Revision as of 14:30, 16 February 2024 by Russ hensel (talk | contribs) (→‎Avoid Reserved Words)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

In programming a constant task is to make up names for things you wish the program to work with. Numbers, names.... functions, objects... classes all need names. There are some good practices in making up name and not so good ones. Python even has an official document PEP 8, I think it is called, that discusses this. I have not found the document all that useful. I will give you my version here.

When to use Good Names

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

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().

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.

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].

     for ix_toy, i_toy enumerate( toys ):
            i_toy.my_index   = ix_toy      # not necessarily a useful example of code 

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:

        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 )

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.

            # 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

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

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 )

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".

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.

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.

      self.monitor_state  = 1                # noun
      plug_adapter        = PlugAdapter()    # noun
      def display_help():                    # verb like


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.

     self.live_graph_lines    = None       # lines on the graph, we keep for later updating

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:

     self.monitor_state  = 1  
     # then....         
     self.monitor_state  = 2  

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: (26) "Python Oddities Explained" - Trey Hunner (PyCon AU 2019) - YouTube and 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

      self.gui       = Gui()
      plug_adapter   = PlugAdapter()

Examples

comming.....

Bad

Good

Too Good