Functions, naming conventions in Python

In summary, the conversation discusses the use of local and global variables, and the convention for naming local variables when using the same name as a global variable. The PEP 8 style guide is mentioned as a resource for naming conventions. The conversation also touches on the importance of avoiding global variables and the need for good naming practices in coding. An example is provided from a project where the user is struggling with renaming variables multiple times, and it is suggested to provide specific examples to better understand the problem at hand.
  • #1
Arman777
Insights Author
Gold Member
2,168
193
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.
 
  • Like
Likes sreerajt
Technology news on Phys.org
  • #3
jedishrfu said:
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
 
  • Sad
Likes jedishrfu
  • #4
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.
 
  • Like
Likes jim mcnamara
  • #5
Don't use global variables. Ever. Then there is no problem.
 
  • Like
Likes jim mcnamara, Arman777, Vanadium 50 and 1 other person
  • #6
pbuk said:
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.
 
  • #7
Arman777 said:
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?
 
  • #8
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
 
  • #9
PeterDonis said:
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.
 
  • Like
Likes Wrichik Basu
  • #10
Arman777 said:
...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.
 
  • Like
Likes Arman777
  • #11
Arman777 said:
ı 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.
 
  • Like
Likes Vanadium 50
  • #12
Arman777 said:
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.
 
  • Like
Likes Arman777 and jack action
  • #13
PeterDonis said:
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.
 
  • #14
PeterDonis said:
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.

PeterDonis said:
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:
  • #15
Arman777 said:
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:
  • Like
Likes Arman777
  • #16
jack action said:
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.
jack action said:
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
jack action said:
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.
 
  • Like
Likes jack action
  • #17
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?
 
  • #18
jack action said:
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.
 
  • Like
Likes PeroK
  • #19
FactChecker said:
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?
 
  • Wow
Likes FactChecker
  • #20
FactChecker said:
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?
 
  • #21
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
jack action said:
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...
 
  • #23
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.
 
  • Like
Likes PeroK
  • #24
jack action said:
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.
 
  • #25
The philosophy: Code Tells You How, Comments Tell You Why

The reasons to comment:

http://www.codeodor.com/index.cfm/2008/6/18/Common-Excuses-Used-To-Comment-Code-and-What-To-Do-About-Them/2293 said:
  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)
 
  • #26
jack action said:
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.

FactChecker said:
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.
 
  • #27
jack action said:
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.
 
  • #28
jack action said:
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.
 
  • #29
Programming can be a messy struggle, especially if you are working in other people's code. Comments can help a lot.
 
  • Like
Likes PeroK
  • #30
FactChecker said:
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;)
 
  • Like
Likes jack action
  • #31
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).
 
  • Like
  • Skeptical
Likes PeroK, PeterDonis and jack action
  • #32
FactChecker said:
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.
 
  • Like
Likes FactChecker
  • #33
I don't know what other people have experienced, but my experience is that there are far more cases of too little commenting than too much, especially from beginning programmers.
 
  • #34
Jarvis323 said:
You should write comments when you expect other people who will read the code won't understand something.
Including Future You.
 
  • Like
Likes hmmm27, PeroK and FactChecker

FAQ: Functions, naming conventions in Python

What are functions in Python?

Functions in Python are blocks of code that perform a specific task. They allow for code reusability and help to organize code into smaller, more manageable parts.

How do you define a function in Python?

To define a function in Python, you use the keyword "def" followed by the function name and parentheses. Inside the parentheses, you can specify any parameters that the function will take in. After the parentheses, you use a colon to indicate the start of the function's code block.

What are naming conventions for functions in Python?

When naming functions in Python, it is recommended to use lowercase letters and separate words with underscores. This makes the function names more readable and follows the PEP 8 style guide.

How do you call a function in Python?

To call a function in Python, you simply use the function name followed by parentheses. If the function takes in parameters, you pass in the values inside the parentheses.

Can functions in Python return values?

Yes, functions in Python can return values using the "return" keyword. This allows for the function to perform a task and then pass the result back to the code that called it.

Similar threads

Replies
5
Views
3K
Replies
5
Views
2K
Replies
3
Views
693
Replies
18
Views
1K
Replies
19
Views
2K
Replies
16
Views
1K
Replies
3
Views
1K
Replies
4
Views
1K
Replies
4
Views
4K
Back
Top