Python - get static information
I need to get static information from one "module" to another. I am trying to write a logger with information about the place of the code from where we are registering. For example, in some file:
LogObject.Log('Describe error', STATIC_INFORMATION)
Static information is class name, file name and function name. I get this from here:
__file__
self.__class__.__name__
sys._getframe().f_code.co_name
But I don't want to write these variables during logging. Can I create some function and call it. For instance:
LogObject.Log('Describe error', someFunction())
How can I use it to get static information?
a source to share
I don't think "static" is the world you are looking for. If you read it right, you want to write a function that will return the file name, class name, and method name of the caller.
Basically, you should use sys._getframe (1) to access the previous frame and work from there.
Example:
def codeinfo():
import sys
f = sys._getframe(1)
filename = f.f_code.co_filename
classname = ''
if 'self' in f.f_locals:
classname = f.f_locals['self'].__class__.__name__
funcname = f.f_code.co_name
return "filename: %s\nclass: %s\nfunc: %s" % (filename, classname, funcname)
Then, from a method somewhere, you can write
logger.info("Some message \n %s" % codeinfo())
a source to share
First, use lowercase names for objects and methods. Use only UpperCase names for class definitions.
More importantly, you need a smart introspective feature in every class.
class Loggable( object ):
def identification( self ):
return self.__class__.__module__, self.__class__.__name__, sys._getframe().f_code.co_name
class ARealClass( Loggable ):
def someFunction( self ):
logger.info( "Some Message from %r", self. identification() )
If all of your classes are subclasses of Loggable, you inherit this identity functionality across all classes.
a source to share