textual icon indicating copy to clipboard operation
textual copied to clipboard

[Feature Request] Pass custom parameters to `App`

Open mustafaquraish opened this issue 4 years ago • 3 comments

(I know textual is still in active development and that this might be in the works, but just throwing it up here to help keep track)

There's no way to pass in and store values inside a class that inherits from App, to store application-level information. For instance, the following code does not work:

class MyApp(App):
    def __init__(self, custom_arg, *args, **kwargs):
        self.custom_arg = custom_arg
        super().__init__(*args, **kwargs)
    async def on_mount(self):
        print(self.custom_arg)
MyApp(5).run()

The cause of this seems the be that in the run() function, a new instance of MyApp is created, which is the instance on which on_mount() is actually caused. This is a bit annoying and requires using global variables to store the parameters we want, which is not ideal.

mustafaquraish avatar Aug 24 '21 04:08 mustafaquraish

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

pwoolvett avatar Aug 28 '21 04:08 pwoolvett

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)

CyberSmash avatar Oct 12 '21 18:10 CyberSmash

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.

Erotemic avatar Jul 24 '22 17:07 Erotemic

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

willmcgugan avatar Oct 25 '22 09:10 willmcgugan

Did we solve your problem?

Consider buying the Textualize developers a coffee to say thanks.

Textualize

github-actions[bot] avatar Oct 25 '22 09:10 github-actions[bot]