Functions, naming conventions in Python

  • Python
  • Thread starter Arman777
  • Start date
  • #1
2,118
179
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.
 

Answers and Replies

  • #4
jack action
Science Advisor
Insights Author
Gold Member
2,207
3,757
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
pbuk
Science Advisor
Gold Member
2,446
1,186
Don't use global variables. Ever. Then there is no problem.
 
  • Like
Likes jim mcnamara, Arman777, Vanadium 50 and 1 other person
  • #6
Vanadium 50
Staff Emeritus
Science Advisor
Education Advisor
27,394
11,493
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
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
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
2,118
179
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
2,118
179
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
Dr Transport
Science Advisor
Gold Member
2,514
638
...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.
 
  • #11
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
ı 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
PeterDonis
Mentor
Insights Author
2020 Award
35,266
13,460
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
2,118
179
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
2,118
179
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:
  • #15
jack action
Science Advisor
Insights Author
Gold Member
2,207
3,757
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:
  • #16
2,118
179
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.
 
  • Like
Likes jack action
  • #17
jack action
Science Advisor
Insights Author
Gold Member
2,207
3,757
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
FactChecker
Science Advisor
Gold Member
6,531
2,608
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.
 
  • #19
PeroK
Science Advisor
Homework Helper
Insights Author
Gold Member
2020 Award
18,154
9,824
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
jack action
Science Advisor
Insights Author
Gold Member
2,207
3,757
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
2,118
179
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...
 
  • #23
Ibix
Science Advisor
Insights Author
2020 Award
8,307
7,711
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 in to most languages - perhaps a favourable speed/precision trade off? None of that really belongs anywhere but the comments.
 
  • #24
FactChecker
Science Advisor
Gold Member
6,531
2,608
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
jack action
Science Advisor
Insights Author
Gold Member
2,207
3,757
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)
 

Related Threads on Functions, naming conventions in Python

Replies
6
Views
1K
Replies
8
Views
4K
Replies
19
Views
1K
  • Last Post
Replies
9
Views
2K
Replies
2
Views
2K
Replies
5
Views
4K
  • Last Post
Replies
4
Views
684
  • Last Post
Replies
11
Views
911
Replies
6
Views
5K
Replies
7
Views
1K
Top