Skip to content

Instantly share code, notes, and snippets.

@impredicative
Last active April 14, 2017 23:05
Show Gist options
  • Save impredicative/041c20a8e9ee153966a85a8a3c69fe81 to your computer and use it in GitHub Desktop.
Save impredicative/041c20a8e9ee153966a85a8a3c69fe81 to your computer and use it in GitHub Desktop.
Python locatable class
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