Code Monkey home page Code Monkey logo

Comments (5)

CyberSmash avatar CyberSmash commented on May 17, 2024 6

Because I came looking for this, The above code is slightly wrong. More correct is:

class MyApp(App):
    def __init__(self, *args, custom_arg, **kwargs):
        self.custom_arg = custom_arg
        super().__init__(*args, **kwargs)
    async def on_mount(self):
        print(self.custom_arg)
# This is the change, no () after MyApp
MyApp.run(custom_arg=5)

from textual.

pwoolvett avatar pwoolvett commented on May 17, 2024

The run method is required to run process_messages in asyncio loop. See https://github.com/willmcgugan/textual/blob/f574294beb733df0cfd17993401713edf5ed7fca/src/textual/app.py#L169

you could change your code to:

class MyApp(App):
    def __init__(self, *args, custom_arg, **kwargs):
        self.custom_arg = custom_arg
        super().__init__(*args, **kwargs)
    async def on_mount(self):
        print(self.custom_arg)
MyApp.run(custom_arg=5)
  • run internally forwards the kwargs only, not args
  • kwargs passed to the run classmethod, not the constructor directly.

EDIT: remove typo, add ref

from textual.

Erotemic avatar Erotemic commented on May 17, 2024

I'm not sure why the base App class couldn't be slightly redesigned so run works either as a classmethod or as an instance method. It makes a lot of sense to "build an instance of the app", and then start it later.

The following instance_run_v1 and instance_run_v2 are two variants showing a proof-of-concept of how this can work with a preconstructed class.

from textual import events
from textual.app import App
from textual.widgets import ScrollView


class DemoApp(App):
    """
    A Textual App to monitor jobs
    """

    def __init__(self, myvar, **kwargs):
        super().__init__(**kwargs)
        self.myvar = myvar

    def instance_run_v1(self):
        """
        An alternative to the run classmethod that lets you preconstruct the instance.
        """
        import asyncio
        async def run_app() -> None:
            await self.process_messages()
        asyncio.run(run_app())

    def instance_run_v2(self,
                        console=None,
                        screen: bool = True,
                        driver=None):
        """
        Another alternative to the run classmethod that lets you preconstruct
        the instance. But it updates the console / screen / etc.

        Requires that log / log_verbosity / title are preset
        """
        import asyncio
        async def run_app() -> None:
            self.console = console or self.console
            self.screen = screen or self._screen
            self.driver = driver or self._driver
            await self.process_messages()
        asyncio.run(run_app())

    async def on_load(self, event: events.Load) -> None:
        await self.bind("q", "quit", "Quit")

    async def on_mount(self, event: events.Mount) -> None:

        self.body = body = ScrollView(auto_width=True)
        await self.view.dock(body)

        async def add_content():
            from rich.text import Text
            content = Text(self.myvar)
            await body.update(content)

        await self.call_later(add_content)


self = DemoApp(myvar='Hello World!')
self.instance_run_v1()
# self.instance_run_v2()

In fact I was able to come up with a backwards compatible change to App that allows run to be used as both an instance or a class method. The following demo runs the code in both ways. The first run uses the class method, then after quitting we create an instance and use the instance method.

from textual import events
from textual.app import App
from textual.widgets import ScrollView
from textual.driver import Driver
from typing import Type
from rich.console import Console
import asyncio


class class_or_instancemethod(classmethod):
    """
    References:
        https://stackoverflow.com/questions/28237955/same-name-for-classmethod-and-instancemethod
    """
    def __get__(self, instance, type_):
        descr_get = super().__get__ if instance is None else self.__func__.__get__
        return descr_get(instance, type_)


class InstanceRunnableApp(App):
    """
    Extension of App that allows for running an instance
    """

    @classmethod
    def _run_as_cls(
        cls,
        console: Console = None,
        screen: bool = True,
        driver: Type[Driver] = None,
        **kwargs,
    ):
        """
        Original classmethod logic
        """
        async def run_app() -> None:
            app = cls(screen=screen, driver_class=driver, **kwargs)
            await app.process_messages()

        asyncio.run(run_app())

    def _run_as_instance(
        self,
        console: Console = None,
        screen: bool = True,
        driver: Type[Driver] = None,
        **kwargs,
    ):
        """
        New instancemethod logic
        """
        if len(kwargs):
            raise ValueError(
                'Cannot pass kwargs when running as an instance method. '
                'Assuming that instance variables are already setup.')
        async def run_app() -> None:
            self.console = console or self.console
            self.screen = screen or self._screen
            self.driver = driver or self._driver
            await self.process_messages()
        asyncio.run(run_app())

    # Allow for use of run as a instance or classmethod
    @class_or_instancemethod
    def run(
        cls_or_self,
        console: Console = None,
        screen: bool = True,
        driver: Type[Driver] = None,
        **kwargs,
    ):
        """Run the app.
        Args:
            console (Console, optional): Console object. Defaults to None.
            screen (bool, optional): Enable application mode. Defaults to True.
            driver (Type[Driver], optional): Driver class or None for default. Defaults to None.
        """
        if isinstance(cls_or_self, type):
            # Running as a class method
            cls_or_self._run_as_cls(
                screen=screen, driver=driver, **kwargs)
        else:
            # Running as an instance method
            cls_or_self._run_as_instance(
                screen=screen, driver=driver, **kwargs)


class DemoApp(InstanceRunnableApp):
    """
    A Textual App to monitor jobs
    """

    def __init__(self, myvar, **kwargs):
        super().__init__(**kwargs)
        self.myvar = myvar

    async def on_load(self, event: events.Load) -> None:
        await self.bind("q", "quit", "Quit")

    async def on_mount(self, event: events.Mount) -> None:

        self.body = body = ScrollView(auto_width=True)
        await self.view.dock(body)

        async def add_content():
            from rich.text import Text
            content = Text(self.myvar)
            await body.update(content)

        await self.call_later(add_content)


DemoApp.run(myvar='Existing classmethod way of running an App')

self = DemoApp(myvar='The instance way of running an App')
self.run()

It would definitely be nice to have this feature in textual. It feels much more intuitive to me to use an instance method with a preconstructed set of widgets forcing the class to have to set itself up. It would certainly make hacking on it easier.

from textual.

willmcgugan avatar willmcgugan commented on May 17, 2024

https://github.com/Textualize/textual/wiki/Sorry-we-closed-your-issue

from textual.

github-actions avatar github-actions commented on May 17, 2024

Did we solve your problem?

Consider buying the Textualize developers a coffee to say thanks.

Textualize

from textual.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.