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

Alternative compose #1847

Merged
merged 12 commits into from
Feb 21, 2023
Merged

Alternative compose #1847

merged 12 commits into from
Feb 21, 2023

Conversation

willmcgugan
Copy link
Collaborator

@willmcgugan willmcgugan commented Feb 20, 2023

I've added an alternative (and complimentary) way of composing widgets.

Building compose methods gets a little awkward at a certain level. Consider this method:

def compose(self) -> ComposeResult:
    yield Foo()
    yield Bar()
    yield Baz()

If I want to wrap that in a Horizontal, the syntax changes:

def compose(self) -> ComposeResult:
    yield Horizontal(    
        Foo(),
        Bar(),
        Baz(),
        id="wrapper"
    )

This change allows widgets to be used as a context manager, to introduce a new level.

def compose(self) -> ComposeResult:
    with Horizontal(id="wrapper"):
        yield Foo()
        yield Bar()
        yield Baz()

Both methods can coexist, but I find there are the following benefits with the context managers:

  • It's easy to wrap something, add a line and indent the contents.
  • The id and other parameters remain at the top.
  • No need to add commas and braces.
  • Adding many widgets doesn't require clumsy looking spat syntax Vertical(*[MyWidget() for _ in range(10)]).

This isn't documented yet. I've only changed internal apps for now. I want to see how we find this.

@davep
Copy link
Contributor

davep commented Feb 20, 2023

Just from the description alone this gets an enthusiastic "oh hell yes!" from me.

src/textual/widget.py Outdated Show resolved Hide resolved
Copy link
Contributor

@rodrigogiraoserrao rodrigogiraoserrao left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this use of context managers!

CHANGELOG.md Outdated Show resolved Hide resolved
src/textual/_compose.py Show resolved Hide resolved
src/textual/_compose.py Show resolved Hide resolved
@ofek
Copy link
Contributor

ofek commented Feb 21, 2023

Very nice!!!

@willmcgugan willmcgugan merged commit f0e454f into main Feb 21, 2023
@willmcgugan willmcgugan deleted the alt-compose branch February 21, 2023 10:46
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.

4 participants