Last active
April 14, 2017 23:05
-
-
Save impredicative/041c20a8e9ee153966a85a8a3c69fe81 to your computer and use it in GitHub Desktop.
Python locatable class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
class Locatable: | |
def __new__(cls, *_args, **_kwargs): | |
# Background: http://eli.thegreenplace.net/2012/04/16/python-object-creation-sequence | |
obj = super().__new__(cls) | |
obj.location = obj._initialization_location() # pylint: disable=protected-access | |
return obj | |
@staticmethod | |
def _initialization_location(): | |
# Background: https://stackoverflow.com/a/42653524/ | |
frame = inspect.currentframe() | |
while frame: | |
if frame.f_code.co_name == '<module>': | |
return {'module': frame.f_globals['__name__'], 'line': frame.f_lineno} | |
frame = frame.f_back | |
@property | |
def name(self): | |
module_name = self.__module__ | |
class_name = self.__class__.__qualname__ # pylint: disable=no-member | |
return module_name + '.' + class_name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment