Skip to content

attr.ibs that will be __name-mangled should be attrs-init-mangled to <name> not ClassName_<name> #619

Open
@graingert

Description

@graingert

all attrs does is remove the leading "_" which is a bit unfortunate

import attr

@attr.s
class Breakfast:
    __spam = attr.ib()
    __eggs = attr.ib()

    @classmethod
    def create(cls):
        return cls(Breakfast__spam=1, Breakfast__eggs=2)

    def with_ham(self, ham):
       return attr.evolve(self, Breakfast__spam=process(ham))

I think it might be nicer as:

import attr

@attr.s
class Breakfast:
    __spam = attr.ib()
    __eggs = attr.ib()

    @classmethod
    def create(cls):
        return cls(**{cls.__spam: 1, cls.__eggs: 2})

    def with_ham(self, ham):
       return attr.evolve(self, **{type(self).__spam: process(ham)})

I currently work around it with

import re

import attr

class _Mangle:
    def __getattr__(self, name):
        return re.sub(pattern=r"\A_", repl="", string=name)

M = _Mangle()


@attr.s
class Breakfast:
    __spam = attr.ib()
    __eggs = attr.ib()

    @classmethod
    def create(cls):
        return cls(**{M.__spam: 1, M.__eggs: 2})


    def with_ham(self, ham):
       return attr.evolve(self, **{M.__spam: process(ham)})

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions