Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

attributes based on properties #245

Closed
blueyed opened this issue Sep 16, 2017 · 8 comments
Closed

attributes based on properties #245

blueyed opened this issue Sep 16, 2017 · 8 comments

Comments

@blueyed
Copy link
Member

blueyed commented Sep 16, 2017

import attr


@attr.s
class Line:
    line = attr.ib()
    counts = attr.ib(default=None)
    _parsed_line = None

    @property
    def counts(self):
        if not self._parsed_line:
            self._parsed_line = (1, 2)
        return self._parsed_line[0]


line = Line('foo')

print(line)
print(line.counts)

Currently this prints:

Line(line='foo')
1

But I like for it to print:

Line(line='foo', counts=1)
1

I.e. it should use the property in the __repr__ output.

Is this possible already maybe?

@RonnyPfannschmidt
Copy link

as far as i can tell this crippled example hides the real use-case

please describe the real use-case, because this example is just horrifying

@RonnyPfannschmidt
Copy link

also note that due to how python works, attrs doesnt see the counts "attribute", only the property is visible

@blueyed
Copy link
Member Author

blueyed commented Sep 16, 2017

My use case is to have attributes (that get reflected in __repr__, but I want to build them lazily, based on some other attributte).
I could use an validator for this maybe, but it should get done lazily.

@blueyed
Copy link
Member Author

blueyed commented Sep 16, 2017

What is so horrifying about the example btw? (it is a trimmed down example after all)

@blueyed
Copy link
Member Author

blueyed commented Sep 16, 2017

I know that the property overwrites the attribute, it is just meant to illustrate the use case.
I think attr might provide support for some callback that is then used as a property or something similar.

@hynek
Copy link
Member

hynek commented Sep 24, 2017

Sounds like #212 all over again?

@blueyed
Copy link
Member Author

blueyed commented Sep 24, 2017

Yes, or at least it is related somewhat in the end after all.

@blueyed blueyed closed this as completed Sep 24, 2017
@zuckerruebe
Copy link

Could someone explain how to use #212 or #568, respectively, to include a "computed field" aka property in the generated repr, please? I can't see it...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants