Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the advantage of a trailing underscore in Python naming?

I am used to naming Python arguments in this way:

my_argument='foo'

what's the advantage if I do this instead:

my_argument_='foo" 

as is recommended by PEP008?

There must be a good reason for the trailing underscore, so what is it?

like image 359
Mario Avatar asked Jan 12 '14 13:01

Mario


1 Answers

There is no advantage of this convention but it might have special meanings in different projects. For example in scikit-learn, it means that the variable with trailing underscore can have value after fit() is called.

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.coef_
AttributeError: 'LinearRegression' object has no attribute 'coef_'

In this code above, when you try to get coef_ attribute of lr object, you will get an AttributeError because it is not created since fit is not called yet.

lr = LinearRegression()
lr.fit(X, y)
lr.coef_

but this time, it will return the coefficients of each column without any errors. This is one of the ways how this convetion is used and it might mean different things in different projects.

like image 199
gunesevitan Avatar answered Oct 07 '22 06:10

gunesevitan