Mario
Mario

Reputation: 941

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?

Upvotes: 22

Views: 11362

Answers (4)

gunesevitan
gunesevitan

Reputation: 964

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.

Upvotes: 13

Daniel Roseman
Daniel Roseman

Reputation: 599778

PEP8 does not recommend this naming convention, except for names that would otherwise conflict with keywords. my_argument obviously does not conflict, so there is no reason to use an underscore and PEP8 does not recommend that you do.

Upvotes: 22

user3002473
user3002473

Reputation: 5074

Usually naming conventions like this don't have any empiric purpose in python (i.e. they don't do anything special) aside from avoiding conflict between keywords. For example, you wouldn't name a variable class would you? You'd name it class_ to avoid conflict with the built-in keyword.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

Exactly what it gives in the PEP: it allows you to use something that would otherwise be a Python keyword.

as_
with_
for_
in_

Upvotes: 38

Related Questions