Skip to main content

python-nameof: a Python implementation of C# nameof operator

This is a follow-up to this project since the author archived it, preferring the varname library which used to cover nameof, but then varname deprecated it.

A Python utility that mimics the C# nameof operator, allowing you to get variable, attribute, or property names as strings at runtime.

It is an essential operator to allow flexible and reliable refactoring, among many other things.

This implementation supports string interpolation, so it's easy to reference variable names when logging, e.g.
log.error(f"{nameof(somevariable)} is incorrect").

Installation

Pip:

pip install python_nameof

My recommendation is to always use uv instead of pip – I personally think it's the best package and environment manager for Python.

uv add python_nameof

Usage

Import:

from nameof import nameof

Simple usage:

foo = 123
nameof(foo)  # Output: 'foo'

You can test it in a simple refactoring operation. For example:

def print_variables(temperature: int)
    print(f"The parameter {nameof(temperature)} is: {temperature}")

The parameter temperature is: 34

If you refactor (e.g. VSCode: press F2 on the variable name) the input parameter from temperature to temperature_celsius, you will get:

def print_variables(temperature_celsius: int)
    print(f"The parameter {nameof(temperature_celsius)} is: {temperature_celsius}")

So the printed name follows the name of the actual parameter after a refactor.

The parameter temperature_celsius is: 34

Additional Parameters

The nameof function supports two optional parameters for formatting the output:

  • wrap_in_chars: Wraps the variable name with the specified string at the start and end.
  • replace_with_whitespace: Removes all occurrences of the specified character(s) from the variable name and replaces them with a whitespace. Accepts a string or a list of strings.

These are especially useful if you are logging to markdown format (printing messages as Markdown), to format variable names as code or to remove underscores for readability.

some_param = 1

# Combine both: wrap in backticks and remove underscores
nameof(some_param, "`", "_")  # Output: '`some param`'

This is useful when generating Markdown documentation or error messages:

def print_variables(temperature_celsius: int)
    print(f"The parameter {nameof(temperature_celsius, "`", "_")} is: {temperature_celsius}")

This will plot a nicely formatted markdown, useful if you do logging in markdown:

The parameter temperature celsius is: 34

Multiple assignments

If a variable is assigned twice, only the first name is returned.

a = b = 1

nameof(a) # returns "a"
nameof(b) # returns "b"

nameof(1) # raises ValueError (see next section below)

Error Handling

If you pass a value or an expression that is not a variable or attribute, nameof raises a ValueError:

nameof(42)            # Raises ValueError
nameof("foo.bar")     # Raises ValueError
nameof("nameof(bar)") # Raises ValueError

More usage examples

nameof() supports string interpolation, so it's easier to reference variable names when logging, allowing for easier refactoring.
In the example below, refactoring the name of second_param will propagate to the printed message without having to manually do it.

def myFuncWithAmazingLogging(first_param: int):
    valid_threshold = 10
    if first_param < 10:
        print(f"The parameter {nameof(first_param)} should be less than {valid_threshold}")

It works for class attributes and instance variables.

class Bar:
    attr = 99
bar = Bar()
nameof(Bar.attr)      # Output: 'attr'
nameof(bar.attr)      # Output: 'attr'

It works also for nested classes.

class Inner:
    @property
    def value(self):
        return 10

class Outer:
    def __init__(self):
        self.inner = Inner()

outer = Outer()
nameof(outer.inner.value)  # Output: 'value'

Release files for python-nameof 2.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-nameof 2.0.2
File Size Uploaded
python_nameof-2.0.2.tar.gz 5.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for python-nameof 2.0.2
File Interpreter ABI Platform
python_nameof-2.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 11.1 kB

Release files / python_nameof-2.0.2.tar.gz

Download URL python_nameof-2.0.2.tar.gz
Size 5.1 kB
Tags Source
SHA-256 checksum
How to use checksums
7b5b72650d88e6ea813e16531f39df0a0504f41f2e68b0e9fd2a41e7ee8c64d9
BLAKE2b-256 checksum
How to use checksums
58c0d0d36e96cabf75419017c1ea8091bca7e4f583499435840c0e9c26ca5f70
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Release files / python_nameof-2.0.2-py3-none-any.whl

Download URL python_nameof-2.0.2-py3-none-any.whl
Size 5.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0046b346b55be6b4818dbe31ba22946334e21ee6568aedd5c513911c837f61df
BLAKE2b-256 checksum
How to use checksums
fbc0806707fc6b8700a64093d81b7ea58a5aff9cdc671bef9ce2dc7778189ca3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Release history Release notifications | RSS feed

This release

2.0.2 This release

2 release files

2.0.1

2 release files

2.0.0

2 release files

1.3.0

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page