Functions, naming conventions in Python

• Python
Gold Member
Sometimes, when I code something, I am naming the local variables in the function same as the global variable. Such as,

Code:
my_var = 13

def iseven(my_var):
if my_var % 2 == 0:
return True
return False

print(iseven(my_var))

As you can see my_var is defined globally but also used locally inside the function. My question is, in these kind of situation, is there a convention for naming the local variables if we want to stick with a base name my_var ?

For instance is this a good naming option

Code:
my_var = 13

def iseven(_my_var):
if _my_var % 2 == 0:
return True
return False

print(iseven(my_var))

or it can be something else.

sreerajt

Gold Member
The PEP 8 style guide may help here:

https://www.python.org/dev/peps/pep-0008/

They have a whole section on naming conventions.
I have looked at it but it doesn't say much or I couldn't see it

jedishrfu
Gold Member
I never like this way of naming variables with similar names. I found it confusing. If you think you need two different variables, then there are most likely two different names available.

I understand you used a simplified example, but let's look at it. my_var would be a terrible name because it is so meaningless. Say, you use age instead. Now we clearly understand what it represents. If your function iseven always refers to age then the proper code would be:

Python:
age = 13

def iseven():
if age % 2 == 0:
return True
return False

print(iseven())

Having the function named age_is_even would probably be a better name though.

But if the function is used in a more general case, then a more suited name should be used for the local variable:

Python:
age = 13

def iseven(number):
if number % 2 == 0:
return True
return False

print(iseven(age))

If you need local stuff, then you probably need a class and use attributes and instance methods.

I would really want to see a case where you need to have different variables with the same name.

jim mcnamara
Gold Member
Don't use global variables. Ever. Then there is no problem.

jim mcnamara, Arman777, Vanadium 50 and 1 other person
Staff Emeritus
2021 Award
Don't use global variables. Ever.
I'm sure there is some use case. Like making debugging more exciting!

Seriously, I am sure that there is some CS reason to use them in weird edge cases, but I can't remember any time a singleton wouldn't have worked better.

Mentor
is there a convention for naming the local variables if we want to stick with a base name my_var ?
Why do you want to stick with a base name my_var? What purpose does that serve?

Gold Member
For instance I am working on scalar fields (in a project that I have mentioned earlier). For classes I am using ScalarField for variables ı am choosing scalar_field and for function names I am using scalarfield. I am also really terrible at naming stuff (really really terrible). For instance PySimpleGUI has two variable names event and values. In another function I am taking these values to do another stuff. So I thought I can name them differently inside the function. I asked this question because

1) I am really bad at naming things
2) I need to re-name things multiple times (like in the example of scalar field )

For this reason without much altering the name I need to change something. I thought putting '_' in front of the variable but it seems that notation is used something else according to PEP8. So I thought there might be some convention but it seem there isnt. I guess I ll just stick to do my thing :p

Gold Member
Why do you want to stick with a base name my_var? What purpose does that serve?
ı am not using that kind of name..that was just a simple example to make my point.

Wrichik Basu
Gold Member
...I need to re-name things multiple times (like in the example of scalar field )...
Welcome to code development. I've been working on python scripts to process data for a couple of years and have renamed the data structures numerous time to get them into a form where they will be useful for the other members of my group and for my own debugging sanity down the road.

Arman777
Mentor
ı am not using that kind of name..that was just a simple example to make my point.
The example has not made any valid point that I can see. It just obfuscates what you are actually trying to do. I suggest telling us what you are actually trying to do; then we can give you useful advice. Asking about something that you aren't going to do just wastes everybody's time.

Mentor
I need to re-name things multiple times (like in the example of scalar field )
Why? Please give a specific example, because I still don't understand what the problem is that you are trying to solve.

Arman777 and jack action
Gold Member
Why? Please give a specific example, because I still don't understand what the problem is that you are trying to solve.
I ll share some part of the code or a put a link real soon.

Gold Member
Why? Please give a specific example, because I still don't understand what the problem is that you are trying to solve.
For instance, look at here

https://github.com/seVenVo1d/grtcgui/blob/main/objects/fields/scalarfield.py

The class name is ScalarField, the variables are named as scalar_field and the get_scalarfield() (or in other functions) I am writing it as scalarfield. You can also look other files from the project page to see the other examples.

I still don't understand what the problem is that you are trying to solve.

First look at here.

https://github.com/seVenVo1d/grtcgui/blob/main/display4D/fieldsGUI/scalarfieldGUI.py

In line 45, I am defining the scalar_field from a user input. After that, I need to use this value in

cd_scalarfield_ep(coord_sys, scalar_field, index_symbol) defined in

https://github.com/seVenVo1d/grtcgui/blob/main/equations/FieldsEP/scalarfieldEP.py

which contains the scalar_field as an input.

My question was, instead of writing
Code:
def cd_scalarfield_ep(coord_sys, scalar_field, index_symbol)
should I write something like
Code:
def cd_scalarfield_ep(coord_sys, _scalar_field_, index_symbol)
or
Code:
def cd_scalarfield_ep(coord_sys, _scalar_field, index_symbol)
something that is different from the scalar_field that we have obtained in line 45

Last edited:
Gold Member
My question was, instead of writing
Code:
def cd_scalarfield_ep(coord_sys, scalar_field, index_symbol)
should I write something like
Code:
def cd_scalarfield_ep(coord_sys, _scalar_field_, index_symbol)
or
Code:
def cd_scalarfield_ep(coord_sys, _scalar_field, index_symbol)
something that is different from the scalar_field that we have obtained in line 45
But they are in different files, so it cannot be confusing.

As for your ScalarFiled class, there is a problem with the naming. You have an object scalar field that contains a scalar field attribute. It is like creating a dog object with a dog attribute. It makes no sense. I would suggest something like the class ScalarField, with the attribute data_set (instead of scalar_field) and the method get (instead of get_scalarfield).

Secondly, for the file scalarfieldEP.py, it might be advantageous to put these functions in a class extended from the class ScalarField (say, a class named ScalarFieldEquation). This way, the function cd_scalarfield_ep(coord_sys, scalar_field, index_symbol) could become covariant_derivative(index_symbol)., a much better name in my opinion (and then you won't have to put the definition in your comments).

So in your file scalarfieldGUI.py (starting at line 45), it becomes:

Python:
scalar_field = values[1]   # Obtaining the scalar field
# Calculation of the covariant derivative
if event == 'Calculate':
index_symbol = values[4]
scalar_field_equation = ScalarFieldEquation(coord_sys, scalar_field)
cd_scalar_field_eqn = scalar_field_equation.covariant_derivative(index_symbol)

Or even:

Python:
# Calculation of the covariant derivative
if event == 'Calculate':
scalar_field_equation = ScalarFieldEquation(coord_sys, values[1])
cd_scalar_field_eqn = scalar_field_equation.covariant_derivative(values[4])

Last edited:
Arman777
Gold Member
It makes no sense. I would suggest something like the class ScalarField, with the attribute user_data
I will consider this. It seems like a good idea.
Secondly, for the file scalarfieldEP.py, it might be advantageous to put these functions in a class extended from the class ScalarField (say, a class named ScalarFieldEquation). This way, the function cd_scalarfield_ep(coord_sys, scalar_field, index_symbol) could become covariant_derivative(index_symbol)., a much better name in my opinion (and then you won't have to put the definition in your comments).

So in your file scalarfieldGUI.py (starting at line 45), it becomes:
this never came to my mind
a much better name in my opinion

Indeed. As I have said earlier I am terrible at naming stuff :p. In this structure, I have to name it something like cd_scalarfield_ep since there are many fields. I will also include other operations. In that case, for the sake of the naming conventions, it might be good a idea to follow your approach.

jack action
Gold Member
A good habit is to avoid writing comments as much as possible. So if you write one, ask yourself: Do I really need that comment? If you find yourself writing one explaining what the method does or what the variable represents, it is probably because you didn't name it properly. This type of information should be obvious from the name alone. So when you read your code, it is like reading a book. For example, with:

Python:
txt = "CompanyX"

x = txt.isalpha()

I have a good idea of what isalpha does and I know that it returns a boolean. No need to read the code for the method.

A method does something, so a verb is somewhat expected in the name.

An attribute is usually just a simple name (like age, color, or latitude). If you find yourself writing person_age and dog_age, maybe you need a person class and a dog class?

Gold Member
A good habit is to avoid writing comments as much as possible. So if you write one, ask yourself: Do I really need that comment? If you find yourself writing one explaining what the method does or what the variable represents, it is probably because you didn't name it properly. This type of information should be obvious from the name alone. So when you read your code, it is like reading a book.
I completely, absolutely, and totally, disagree with this. This is the opposite of most of the advice I have to give to beginning programmers.

PeroK
Homework Helper
Gold Member
2021 Award
I completely, absolutely, and totally, disagree with this. This is the opposite of most of the advice I have to give to beginning programmers.
Many years ago, when I was in charge of a team of programmers, I was looking at a programme and there seemed to be no relation between the comments and the code. Then I noticed the comments had a certain style that I recognised as my own!

This programmer had copied one of my old programmes as a starting point, changed the code (of course) but left the comments as they were!

What do you make of that?

FactChecker
Gold Member
I completely, absolutely, and totally, disagree with this. This is the opposite of most of the advice I have to give to beginning programmers.
Care to elaborate on that?

Gold Member
I think writing comments is a good practice at any level (from beginner to advanced programmer). However, it's also necessary to write clear and understandable code. Like in the case of
his way, the function cd_scalarfield_ep(coord_sys, scalar_field, index_symbol) could become covariant_derivative(index_symbol)., a much better name in my opinion (and then you won't have to put the definition in your comments).
Even though my comments are explicit, a subtle change in the code structure can make the code more readable...But during this process, the comments are also critical...

Gold Member
I kind of agree with the coding horror article, but it takes things too far in my opinion. Certainly there's value in writing readable code with good variable and method names, but that can only take you so far. The square root example in that link is just about ok - you can google square root approximation if you're trying to debug. But I'd say you at least want to name the algorithm (or provide a reference in a less trivial case). And you probably ought to explain why you aren't using the sqrt function that's built into most languages - perhaps a favourable speed/precision trade off? None of that really belongs anywhere but the comments.

PeroK
Gold Member
Care to elaborate on that?
Using your analogy of reading a book, the code is like reading "War and Peace" and the comments are like the Cliff Notes. In the comments, you are free to position any summaries, references, analysis, explanations, descriptions of special conditions, footnotes, etc. wherever you want without worrying about whether it will compile. The use of comments is too varied for any brief explanation and attempting more would cause my bloodpressure to get too high.

Gold Member
The philosophy: Code Tells You How, Comments Tell You Why

The reasons to comment:

1. In the styles of Javadoc, RubyDoc, et cetera for documenting APIs others will use.
2. In the off chance it really is that complex: For example, on a bioinformatics DNA search function that took 5 weeks to formulate and write out. That's how rare it is to have something complex enough to warrant comments.
3. TODOs, which should be the exception, not the rule
4. Explaining why the most obvious code wasn't written. (Design decisions)

Mentor
If you find yourself writing one explaining what the method does or what the variable represents, it is probably because you didn't name it properly. This type of information should be obvious from the name alone.

I completely, absolutely, and totally, disagree with this. This is the opposite of most of the advice I have to give to beginning programmers.
I'm somewhere between these two viewpoints, but probably closer to that of FactChecker. Well-chosen names for variables and methods are essential, but these alone don't give the complete story. For example, does the method return a value? If so, what does the value represent, and what is the range of possible return values? If the method returns a boolean, it's pretty clear what the possible return values are, but for any other return type, what is returned should be clearly explained.

If the method has parameters, they, too, should be well-chosen so as to be meaningful. A comment for each can convey the range of values that are appropriate for the method, as well as information about exceptions that could be thrown under certain conditions.

Gold Member
The philosophy: Code Tells You How, Comments Tell You Why

The reasons to comment:
There are a multitude of other reasons. Some examples are:
I converted MATLAB code to other languages and found that leaving the MATLAB code as comments was very helpful to MATLAB people.
It is often useful to define your coordinate systems where they are being used, especially where a lot of conversions are being done.
There are a lot of bit manipulations that are routine to the programmer at that time but become obscure without some comments.
References to documents and equations in books and articles that are being implemented in the code.
Documenting special conditions that would cause errors returned and the return codes at the top of the file, rather than scattered around in the code variables.
Comments allow one to clarify the code over time where needed without any modifications of the actual code.
Clarifying code for your use that someone else programmed. What was clear to him may not be clear to you. In fact, you may want to put in a comment as a guess until you are more familiar with the subject.
It is hard to describe all the multitude of reasons to use comments. I do not recommend discouraging comments due to some idealistic principle.

The philosophy: Code Tells You How, Comments Tell You Why

The reasons to comment:
#2 is the real problem. Who decides what "really is that complex"? I enjoy coding but work in a job where knowing how to code is a "desirable" - so a lot of code I write really is that complex according to most of my colleagues, although it's all fairly basic stuff from my perspective. So I write a lot of comments.

Gold Member
Programming can be a messy struggle, especially if you are working in other people's code. Comments can help a lot.

PeroK
Jarvis323
Programming can be a messy struggle, especially if you are working in other people's code. Comments can help a lot.
And sometimes hurt a lot too;)

jack action
Jarvis323
I'm a minimal commenter as well, but agree with Ibix. You should write comments when you expect other people who will read the code won't understand something.

The problem with comments is that you can write anything in a comment and the code will compile. Each comment introduces a long term vulnerability since it will need to be updated and synchronized with the code as it changes. The more comments you have, the more work that becomes, and the less likely a person is to be diligent in updating them. In general, you cannot rely on them to be accurate. And, if there are too many mundane comments, the reader may just stop reading them and then miss the important ones (like the boy who cried wolf).

PeroK, PeterDonis and jack action
Mentor
Programming can be a messy struggle, especially if you are working in other people's code. Comments can help a lot.
The bulk of time in the software development life cycle (SDLC) is spent on maintenance, usually done by someone other than the original developer, who is likely off in another job, perhaps in a different company. Code steps that seemed trivial to the original developer might not be so to someone else who is tasked with fixing bugs that the code generated. Comments can help this person, especially if they have been kept up to date and are correct explanations of what the code is doing.

FactChecker