Python Names

From OpenCircuits
Jump to: navigation, 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. 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.

Avoid Reserved Words

Reserved words are woods 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.

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

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.





Too Good

Personal tools