1

I run into a function but not quite understand it. I am not sure it is a convention or has a meaning. what does the _p, where did the _p enter the function. It would be much appreciated if you can give me some explanation on the for loop here.

 def contraction_mapping(S, p, MF, params, beta=0.75, threshold=1e-6, suppr_output=False): ''' Initialization of the state-transition matrices: describe the state-transition probabilities if the maintenance cost is incurred, and regenerate the state to 0 if the replacement cost is incurred. ''' ST_mat = np.zeros((S, S)) p = np.array(p) for i in range(S): for j, _p in enumerate(p): if i + j < S-1: ST_mat[i+j][i] = _p elif i + j == S-1: ST_mat[S-1][i] = p[j:].sum() else: pass R_mat = np.vstack((np.ones((1, S)),np.zeros((S-1, S)))) 
2
  • 6
    There's no magic here, it's just to avoid a naming conflict between the already extant p variable. This is generally bad practice (precisely because it harms readability and results in questions like this!), but to each their own. Commented Mar 30, 2017 at 21:54
  • 1
    @ColinBasnett : It might sometimes improve readability. It can be some kind of placeholder (a variable which must be defined, but won't be used later). Instead of just using _, it's possible to describe the ignored variable. E.g. [(x,z) for x, _y, z in coordinates]. Commented Mar 30, 2017 at 22:09

1 Answer 1

2

See PEP8 for details on many python style conventions. In particular, you can find the description of a single leading underscore here:

https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles

_single_leading_underscore : weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

In the loop above, this is somewhat of a misuse, as they are only using _p to avoid clashing with the existing name p. These variable names are not great obviously. The _p are items of the array provided by enumerate, while p is the entire array as well (locally overriding the original p parameter passed in).

As a side note, the loop itself is somewhat awkward, and could be simplified and optimized (mostly fallout from using better ranges instead of pass, and avoiding recalculating the sum repeatedly).

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't apply to the code in question though, since the _p here is local to the function
"_p to avoid clashing with the existing name p". That might have been a valid reason for some other code. But a few lines before : p = np.array(p) :-/ Conclusion : this code isn't meant to be read, and might have been translated from FORTRAN.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.