__FILE__ and __LINE__ in Python

__FILE__ and __LINE__ in Python

Sunday 3 October 2004

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 thePython 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.

你可能感兴趣的:(__FILE__ and __LINE__ in Python)