Skip to main content

A Python implementation of the C# nameof operator.

Project description

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'

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 validate(some_param):
    if some_param < 0:
        # Prints: The parameter `someparam` must be positive.
        print(f"The parameter {nameof(some_param, wrap_in_chars='`', replace_with_whitespace='_')} must be positive.")

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'

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_nameof-2.0.0.tar.gz (4.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_nameof-2.0.0-py3-none-any.whl (5.8 kB view details)

Uploaded Python 3

File details

Details for the file python_nameof-2.0.0.tar.gz.

File metadata

  • Download URL: python_nameof-2.0.0.tar.gz
  • Upload date:
  • Size: 4.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.3

File hashes

Hashes for python_nameof-2.0.0.tar.gz
Algorithm Hash digest
SHA256 9d49442c673622c7c7262ef282ccba004a52a900dd63cc7d7bb9410ba54fb3f0
MD5 04099d22df77963bd63788ec2e64a79d
BLAKE2b-256 f90aab568f59b8de9bd47854342a5b5693e7b638bd9d2ecf58fc4d233d14c125

See more details on using hashes here.

File details

Details for the file python_nameof-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: python_nameof-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.3

File hashes

Hashes for python_nameof-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 682bd426746e86e5a4dc5979c912c84e44010ef7cff75d8a4ef3eb543ba05907
MD5 ccaa134bfc4283a88ee7029307aed595
BLAKE2b-256 16ec8687974f2a7bce7af57183510b3ce179ccd4ca6e23cdd8e0da30acc10dbe

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page