nameof
The `nameof` library, version 0.0.1, provides a simple Python function to retrieve the string name of a variable or attribute, similar to C#'s `nameof` operator. It was released in February 2020 and has not seen further updates. Its author explicitly recommends using the more actively maintained `varname` library for this functionality, indicating that `nameof` was a "toy project."
Common errors
-
NameError: name 'nameof' is not defined
cause The `nameof` function was called without being properly imported or the `nameof` package was not installed.fixEnsure the package is installed (`pip install nameof`) and the function is imported correctly at the top of your file: `from nameof import nameof`. -
AttributeError: 'SomeType' object has no attribute 'some_attribute' (when using nameof on an attribute that exists)
cause This error likely indicates `nameof` is failing to correctly parse the expression or access the frame information due to its underlying implementation limitations, especially with certain object types or dynamic contexts. It's a manifestation of its 'gotcha' warnings regarding reliability.fixSimplify the expression passed to `nameof`. Ensure the attribute access is direct and not part of a more complex chain. If the issue persists, consider using a literal string for the name or switching to the `varname` library which may handle more edge cases.
Warnings
- breaking The author of the `nameof` library explicitly recommends using the `varname` library instead. `nameof` is considered a "toy project" and is not actively maintained, making `varname` the preferred and more robust solution for this functionality.
- gotcha The `nameof` library (version 0.0.1) relies on `sys._getframe` for its functionality, which is a CPython-specific implementation detail. This can lead to unexpected behavior or outright failure on other Python implementations (e.g., PyPy, Jython, IronPython).
- gotcha The `nameof` function has limitations with complex expressions, multiple calls on a single line, or nested parentheses in strings. It might return an incorrect or truncated name in such scenarios.
Install
-
pip install nameof
Imports
- nameof
from nameof import nameof
Quickstart
from nameof import nameof
def example_function():
my_variable = 123
another_name = 'hello'
print(f"The name of 'my_variable' is: {nameof(my_variable)}")
print(f"The name of 'another_name' is: {nameof(another_name)}")
class MyClass:
def __init__(self, value):
self.value = value
instance = MyClass(42)
print(f"The name of 'instance.value' is: {nameof(instance.value)}")
example_function()