Skip to content

Use type hints in action args/kwargs #571

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

Merged
merged 2 commits into from
Aug 10, 2023
Merged

Use type hints in action args/kwargs #571

merged 2 commits into from
Aug 10, 2023

Conversation

adamghill
Copy link
Owner

When type annotations are used in args or kwargs in a method used for an action, Unicorn will attempt to coerce the argument into the type annotation. Solves for #514.

# test_component.py
from django_unicorn.components import UnicornView
from datetime import datetime

class TestComponent(UnicornView):
    def check_datetime(self, _datetime: datetime):
        # the `datetime` type annotation tells Unicorn to convert `_datetime` into a `datetime` object
        assert isinstance(_datetime) is datetime
<!-- test-component.html -->
<div>
  <button u:click='check_datetime("2020-09-12T01:01:01")'>check with a static string</button>
  <button u:click='check_datetime("{{ date_example|date:'c' }}")'>check with a dynamic string</button>
  <button u:click='check_datetime({{ date_example|date:'U' }})'>check with epoch (notice no quotes around the arg to check_datetime)</button>
</div>

@winrid
Copy link

winrid commented Aug 9, 2023

This is a nice improvement, but I think accessing a datetime in __str__ will still break.

@adamghill
Copy link
Owner Author

@winrid Can you provide a test or example code so I can replicate?

@winrid
Copy link

winrid commented Aug 9, 2023

@adamghill I'm on my phone but I think if you just return obj.format() where obj is a datetime it breaks when using that object. Just use it in a select or something:

def __str__():
    return mydatetimemodelfield.format()

Will throw because my date is a str on deserialization.

@adamghill adamghill merged commit f956cae into main Aug 10, 2023
@adamghill adamghill deleted the action-type-hints branch August 10, 2023 12:52
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