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

Support adding class variables to class through assignment #8723

Open
PeterJCLaw opened this issue Apr 25, 2020 · 5 comments
Open

Support adding class variables to class through assignment #8723

PeterJCLaw opened this issue Apr 25, 2020 · 5 comments

Comments

@PeterJCLaw
Copy link
Contributor

Mypy supports adding items to self during test setUp, which is great. However in many cases it's useful to be able to add items to the class during setUpClass (or Django's setUpTestData).

import unittest

class Tests(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        cls.foo = 42  # "Type[Tests]" has no attribute "foo"

    def test_foo(self) -> None:
        print(self.foo)  # "Tests" has no attribute "foo"

Adding a ClassVar allows for a workaround to this, however it would be nice if that wasn't needed.

@msullivan
Copy link
Collaborator

Yeah, adding to a class through a class variable write could be handy, though I doubt it is really on the roadmap for us to implement. There ought to be an issue open for it but I couldn't find one, so I'll leave this open.

@msullivan msullivan changed the title Support unittest.setUpClass Support adding class variables to class through assignment Apr 27, 2020
@PeterJCLaw
Copy link
Contributor Author

Ah, I'd assumed that the support for setUp was specific to unittest handling. Is it just general handling around adding properties to instances? (I had thought that mypy would normally error if you tried to add properties to instances)

@rbharadwaj9
Copy link

@PeterJCLaw can you elaborate on your workaround to this problem? I tried typing my variables in setUpClass with ClassVar but it doesn't seem to help. I think I'm going it wrong.

@PeterJCLaw
Copy link
Contributor Author

I think I worked around this by adding the variables to the class and marking them as ClassVar there.
For example see the variable srcomp_instance in the following: https://github.com/PeterJCLaw/srcomp/blob/d3839d4578728f17a052ce934e8f6fe05a38dfad/tests/test_comp.py#L13-L19

@rbharadwaj9
Copy link

That worked for me. Thanks!

catern added a commit to catern/rsyscall that referenced this issue Feb 8, 2022
I couldn't find any prior art for asyncSetUpClass, so this is a bit
hacky, but it's the obvious way to implement it, and it works fine for
rsyscall.

Annoyingly mypy requires us to explicitly declare the class variables,
see python/mypy#8723
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants