3

Short Question: I can find the line number when a function called as in mentioned here

Similarly, how can I find column number?

Long Question:

def col():
  return something

print("result", col(), col(), col())

should return different numbers from each other, the same numbers whenever this print function is called.

How can I make this?

EDIT:

My workaround right now is as follows:

import inspect
def cid():
  f = inspect.currentframe().f_back
  caller_id = (f.f_lineno, f.f_lasti)
  return caller_id

print((cid(), cid(), cid(), cid(), cid()))
print((cid(), cid(), cid(), cid(), cid()))
print((cid(), cid(), cid(), cid(), cid()))
print((cid(), cid(), cid(), cid(), cid()))

print((cid(),
        cid(),
        cid(),
        cid(),
        cid()))

works as expected (for now). This prints:

((8, 30), (8, 36), (8, 42), (8, 48), (8, 54))
((9, 65), (9, 71), (9, 77), (9, 83), (9, 89))
((10, 100), (10, 106), (10, 112), (10, 118), (10, 124))
((11, 135), (11, 141), (11, 147), (11, 153), (11, 159))
((13, 170), (14, 176), (15, 182), (16, 188), (17, 194))

Problem: I don't know what f_lasti brings exactly at a moment.

Community
  • 1
  • 1
ceremcem
  • 3,900
  • 4
  • 28
  • 66

1 Answers1

2

As can be seen in the official documentation, it does return the index of the last executed byte in the bytecode. That is basically the column, but not in sourcecode, but in bytecode. You can get the disassembly of the code via dis.dis() to make sense of the values in f_lasti:

import inspect
import dis
def cid():
  f = inspect.currentframe().f_back
  dis.dis(f.f_code)
  caller_id = (f.f_lineno, f.f_lasti)
  return caller_id

print((cid(), cid(), cid(), cid(), cid()))

I don’t think python keeps the mapping between bytecode and column after compilation. If I’m right it is basically impossible to get the column number.

Chronial
  • 66,706
  • 14
  • 93
  • 99