Skip to content

Instantly share code, notes, and snippets.

@aizquier
Created December 3, 2019 16:33
Show Gist options
  • Save aizquier/34c37f900cf0023829041a6447bbd951 to your computer and use it in GitHub Desktop.
Save aizquier/34c37f900cf0023829041a6447bbd951 to your computer and use it in GitHub Desktop.
python3: Overloads the builtin `print()` function to print the file and line number where the print occurs.
'''
Overloads the builtin `print()` function to print the file and line number
where the print occurs, similarly to Javascript's `console.log()`.
Useful when in development. Just import this file at the top of your project.
'''
import builtins
import inspect
import os
def prnwrapper(fn):
def print_with_filename_and_linenumber(*args, **kwargs):
current_line = inspect.currentframe().f_back.f_lineno
current_file = os.path.basename(inspect.getfile(inspect.currentframe().f_back))
args = ["[%s:%d] " % (current_file, current_line)] + list(args)
fn(*args, **kwargs)
return print_with_filename_and_linenumber
builtins.print = prnwrapper(builtins.print)
@aizquier
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment