function parameter names starting with underscore

Viewed 338

Is there any difference between parameters starting with underscore and normal parameters in python ?

eg:

def fun1(_data, _val):
    ....
    ....

def fun2(data, val):
    ....
    ....

 

Why I asked this question is because, in pycharm I could see the parameter data as blurred (It wasn't using anywhere) and the parameter _data as non-blurred (which was also not using anywhere in the function)

1 Answers

There is no difference in practice, and for function parameters you wouldn't really do this.

In python, there is a convention that a single underscore means the var/method is private, so _data should not be used by 3rd party apps. You'd often use this for e.g variables only available within a class.

Double underscore vars, e.g. __data is just an extra level of "don't use this from outside the class".

Usually, you'd use these to indicate to other devs that they shouldn't access eg. classname._var, but you would instead provide some kind of getter or setter method instead.

Related