0

I am writting a code and i already know i'll have to change some instructions when i'll have more information. I already know the specific lines i'll have to change, but since the code is a bit long, i'd like to prepare the moment i'll have to change those lines, by printing the n° of those lines. Actually i'd like something like a this_line() function that would work like this :

1 
2 
3 print('this line is the n°'.format(this_line())
4

>>> this line is the n°3

Can i do this without converting my code in .txt and counting the lines ?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • It might be useful in a specific niche case, but aren't you sure you'd rather organize your code, so you don't have to look through one single big function ? It would help you immensely, rather than printing the # of a line. – Jean Rostan Apr 18 '18 at 14:50
  • I need to open many different files with different names, and i dont have the name of those files for the moment, i just have some 'training files' that ables to test if the code is correct, but i'll have to change one by one all of the files names i open in the code when i'll have the final files – Aurélien Tronc Apr 18 '18 at 14:55
  • Then, think about it differently. Use variables at the top of your module, which uses for now your training files, and use these variables in your code instead of hard coding the values. Then you will only have to change the top variables ? – Jean Rostan Apr 18 '18 at 14:57
  • Possible duplicate of [filename and line number of python script](https://stackoverflow.com/questions/3056048/filename-and-line-number-of-python-script) – raul.vila Apr 18 '18 at 15:13

1 Answers1

3

The inspect module has you covered. Just import inspect, and run:

inspect.currentframe().f_lineno

to get the line number of the currently executing frame.

Note, this is a feature specific to CPython (the reference interpreter), per the docs:

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

I'm unclear on whether the concept of a frame and its line number will exist elsewhere, but this will work fine on the reference interpreter. It's possible that this is portable (there is no note claiming otherwise), but I can't be sure:

inspect.stack()[0].lineno
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271