Skip to content

Conversation

@wolph
Copy link
Contributor

@wolph wolph commented Mar 12, 2022

The Python class datamodel normally supports the set_name method on a class, allowing you to do:

class A:
    x = C()  # Automatically calls: x.__set_name__(A, 'x')

This is a very useful feature for custom fields but the Model metaclass has removed this functionality. With this small patch it's re-added.

Description

Add __set_name__ support to the Model metaclass
Add a __set_name__ type stub to Field because mypy doesn't support __set_name__ yet: python/mypy#8057
Added a test to confirm it works

Motivation and Context

I'm building a native Postgres enum field, and having the name of the field available in the class makes this a lot easier.
Instead of doing this:

class SomeModel(Model):
    some_enum = EnumField('some_enum')

I can now do:

class SomeModel(Model):
    some_enum = EnumField()

How Has This Been Tested?

I've added a simple test to confirm that the test works. And I've run make test and make style ci

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added the changelog accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

@wolph
Copy link
Contributor Author

wolph commented Mar 12, 2022

Since we're testing with pytest, it might be beneficial to allow assert statements within the tests at least :)
https://docs.pytest.org/en/latest/how-to/assert.html

@coveralls
Copy link

coveralls commented Mar 12, 2022

Pull Request Test Coverage Report for Build 1972061400

  • 5 of 5 (100.0%) changed or added relevant lines in 2 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.008%) to 93.626%

Totals Coverage Status
Change from base Build 1938506197: -0.008%
Covered Lines: 5173
Relevant Lines: 5457

💛 - Coveralls

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

Successfully merging this pull request may close these issues.

2 participants