Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

Start using attrs instead of namedtuple #4

Closed
balloob opened this issue Feb 7, 2018 · 3 comments
Closed

Start using attrs instead of namedtuple #4

balloob opened this issue Feb 7, 2018 · 3 comments

Comments

@balloob
Copy link
Member

balloob commented Feb 7, 2018

attrs is a Python package that allows you to write simple classes without any boilerplate. It's like a namedtuple, but better.

It makes it a lot easier to write small classes to pass data around. We use namedtuple 41 times currently in our codebase.

Normally I am not the person to propose adding dependencies to core, however I noticed that aiohttp started using attrs 2 weeks ago (aio-libs/aiohttp#2690) and thus it is already installed for a base install of Home Assistant.

Python 3.7 includes something similar to attrs called "Data Classes". However, it depends on PEP 526 which was only included in Python 3.6.

I think that using attrs can make our code easier to use. It also does not add any runtime costs since it does the work when the class is declared, not when a property is requested.

@balloob
Copy link
Member Author

balloob commented Feb 7, 2018

One of the advantages of attrs over namedtuple is default values. Now I tend to convert a namedtuple to a class whenever I want to add default values to avoid this:

Message = namedtuple('Message', ['topic', 'payload', 'qos', 'retain'])
Message.__new__.__defaults__ = (0, False)

@pvizeli
Copy link
Member

pvizeli commented Feb 8, 2018

Looks amazing. I don't like namedtuple anyway :)

@balloob
Copy link
Member Author

balloob commented Feb 15, 2018

We're using attrs now!

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants