Skip to content

Instantly share code, notes, and snippets.

@gerryjenkinslb
Last active December 21, 2020 21:17
Show Gist options
  • Save gerryjenkinslb/ea4b5b5d042018e791be66ac208599fb to your computer and use it in GitHub Desktop.
Save gerryjenkinslb/ea4b5b5d042018e791be66ac208599fb to your computer and use it in GitHub Desktop.
from inspect import getframeinfo, currentframe
import os
def line_at(style=None):
"""
returns string with caller filename function name and line number
style parameter (sample string):
'long': 'File /Home/user/xyz.py, in foo(), Line 233'
'medium': 'File /Home/user/xyz.py,Line 233'
'short': 'xyz.py:233'
default: '/Home/user/xyz.py:233'
"""
cf = getframeinfo(currentframe().f_back) # get callers frame info
if style == "long": # File /Home/user/xyz.py, in foo(), Line 233
return f"File {cf.filename}, in {cf.function}(), Line {cf.lineno}"
elif style == "medium": # File /Home/user/xyz.py,Line 233
return f"File {cf.filename}, Line {cf.lineno}"
elif style == "short": # xyz.py:233
return f"{os.path.basename(cf.filename)}:{cf.lineno}"
else: # /Home/user/xyz.py:233
return f"{cf.filename}:{cf.lineno}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment