Attrs: option for disable strips the underscores

Created on 9 Jun 2018  路  7Comments  路  Source: python-attrs/attrs

Add an option to disable strips the underscores
http://www.attrs.org/en/stable/init.html#private-attributes

I need to create class with _id attribute and this is not possible with attrs at this moment

Feature

Most helpful comment

_ stripping should be optional IMHO. I am blocked on adding a _thing to my class which also has a thing attribute (don't ask, I'm doing a source port). Even if you are right about private attributes "not existing", this choice encoded into the software seems contrary to the stated goals of not "slowing down your code".

All 7 comments

You can have an _id attribute just fine; it鈥檚 just the __init__ signature is going to be __init__(_id):

In [1]: import attr

In [2]: @attr.s
   ...: class C:
   ...:     _id = attr.ib()
   ...:

In [3]: C(1)
Out[3]: C(_id=1)

Problem is in __init__ method

In [1]: import attr

In [2]: @attr.s
   ...: class C:
   ...:     _id = attr.ib()
   ...:

In [3]: C(**{'_id': 1})
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument '_id'

How to add _id as is without stripping into __init__ kwargs ?

_ stripping should be optional IMHO. I am blocked on adding a _thing to my class which also has a thing attribute (don't ask, I'm doing a source port). Even if you are right about private attributes "not existing", this choice encoded into the software seems contrary to the stated goals of not "slowing down your code".

Furthermore, the documentation states that "There really isn鈥檛 a right or wrong, it鈥檚 a matter of taste." but one way is not allowed in the software so there is clearly a wrong way to do it according to attrs. This is misleading.

This issue has come up in some generated code before, for example like this.

@attr.s
class A:
    _ = attr.ib()

File "<attrs generated init __main__.A>", line 2
    self._ =
             ^
SyntaxError: invalid syntax

Any updates on this topic?

A side note, you can use cattrs to structure classes with underscore attributes:

import attr
import cattr

@attr.s
class C:
  _id = attr.ib()

cattr.structure({'_id': 1}, C)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

aragilar picture aragilar  路  17Comments

peteroconnor-bc picture peteroconnor-bc  路  9Comments

Bananaman picture Bananaman  路  7Comments

RonnyPfannschmidt picture RonnyPfannschmidt  路  7Comments

gvoysey picture gvoysey  路  10Comments