Syntax question : how do you differentiate local and class variables?

Godot Version

All of them.

Question

There’s a question I’ve been asking myself for a long time now (I’ve been developing on Godot for 4 years now). I didn’t find a satisfying answer (for me though) on the coding guidelines page.

How do you deal with variable naming, especially when you want to differentiate local variables of a function and class variables ?

Let’s say something like this :

extends Node

# "private" variable naming with an underscore is OK for me
var _some_stuff : int = 0

# No underscore : I tell myself that this value is "public" to other classes
var speed : float = 0

func my_epic_callback():
    # Here some code that will use temporary variables potentially named speed

Here are some thoughts :

  • I remember one time I decided to use some kind of “m_” prefix, but things were getting ugly on exported variables as the UI was full of “m_”.
  • I’d like to avoid naming like the_speed, my_speed, well… at least tmp_speed
  • Finally, I ended using the pythonic self keyword to help me identify which is a class variable and which is just a temporary one
  • As I’m writing the previous line, I realize that using self.speed doesn’t allow me to create a local temporary variable named speed, I guess I’d have a variable shadowing warning
  • In the same way, I tend to call built-in functions without self, and class functions with the self prefix, not really better

I’m quite sure someone here has the epic final answer and free me from this burden !

I don’t have a great answer for this and personally I simply don’t have a naming scheme to differentiate between local and class level.
Local for GDScript is entirely functions and by design a function should be very short and do one thing. There should never be difficulty in determining what is a local variable since its declaration should be staring at you (the entire function on screen).
In your example something as simple as
var n:float = speed
But maybe refined depending on what you are going to do with the speed value locally.

Sometimes I find it better to avoid naming a variable by just a letter, especially on complex calculations.

Don’t exist a rule for that, is more preference, but what i generally do is:

In script scope:

  • Underline prefix for internal variables/functions.
  • No prefix for public variables/functions.
  • No one letter/random words for variables/functions.

In function/method scope:

  • Parameters receive a p_ prefix to indicate they are parameters.
  • Generally no prefix for other variables created along the function, unless they collide with other name from script scope or inheritance, in this case i use a l_ prefix to indicate this variable is a local from this scope.
  • One letter/random words is valid IF i don’t use them more than in 4~5 lines, if i need them along a extense function the name should be clear about what they hold.