Skip to content

Instantly share code, notes, and snippets.

@GadgetSteve
Last active June 27, 2022 06:42
Show Gist options
  • Save GadgetSteve/5dfef779ca679bc8301b2c83047666b7 to your computer and use it in GitHub Desktop.
Save GadgetSteve/5dfef779ca679bc8301b2c83047666b7 to your computer and use it in GitHub Desktop.
Importable execution position in python
"""
Importable get called from file & location.
Based on a tweet by Ned Batchelder @nedbat
"""
import inspect
def where_am_i():
""" Return the current filename and line number. """
bf = inspect.currentframe().f_back
return (bf.f_globals.get("__file__", "interactive"), bf.f_lineno)
if __name__ == "__main__":
print(f"At {where_am_i()[1]} of {where_am_i()[0]}")
@GadgetSteve
Copy link
Author

GadgetSteve commented Jun 26, 2022

This would typically be used something like:

from where_am_i import where_am_i

# At some point in your code
print(f"At {':'.join(str(w) for w in where_am_i())}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment