A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://nedbatchelder.com/blog/200410/file_and_line_in_python.html below:

__FILE__ and __LINE__ in Python

Sunday 3 October 2004This is nearly 21 years old. Be careful.

In C++, if you want your code to talk about itself, you often use the predefined magic macros __FILE__ and __LINE__ to get the filename and line number of the current line:

// Use this macro if you can't write the code yet.
#define NOTYET()    NoCodeYet(__FILE__, __LINE__);

void NoCodeYet(const char * pszFile, int nLine)


{
    fprintf(stderr, "No code yet at %s(%d)\n", pszFile, nLine);
}

//...

void ComplicatedFunctionFromTheFuture()


{
    NOTYET()       // I'll get to this later.
}

This provides a convenient way to leave breadcrumbs that will direct you to the spot in the code later.

How to do it in Python? With help from the Python Cookbook, I created this. It uses scary functions from sys (_getframe has a leading underscore and is described as “for internal and specialized uses only”):

def _functionId(nFramesUp):
    """ Create a string naming the function n frames up on the stack.
    """
    co = sys._getframe(nFramesUp+1).f_code
    return "%s (%s @ %d)" % (co.co_name, co.co_filename, co.co_firstlineno)

def notYetImplemented():


    """ Call this function to indicate that a method isn't implemented yet.
    """
    raise Exception("Not yet implemented: %s" % _functionId(1))

#...

def complicatedFunctionFromTheFuture():


    notYetImplemented()

This goes one further than the C++ technique, by providing the function name as well as the file and line.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4