Comments (5)
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.
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.
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.
https://github.com/Textualize/textual/wiki/Sorry-we-closed-your-issue
from textual.
Did we solve your problem?
Consider buying the Textualize developers a coffee to say thanks.
from textual.
Related Issues (20)
- When TextArea is on a non-default screen, the text of the active line is hidden HOT 1
- `CollapsibleTitle.action_toggle` name clash HOT 1
- Cannot bind to Control+Enter or Shift+Enter for chat-like behavior in TextArea
- Provide a method to unmount and mount current Screen or Widget for python hot-reload HOT 1
- `Select` `OptionHighlighted` message leakage
- Errors in devtools on startup - possibly related to tooltip cleanup HOT 2
- `TabbedContent` styling affects child widgets HOT 1
- `TabbedContent` message mixup if `Tabs` inside a `TabPane`
- Mouse-driven focus does not behave as expected. HOT 2
- `Tabs.Cleared` documentation a little ambiguous HOT 3
- Disabled widgets prevent mouse scrolling HOT 1
- Discord invite link not working HOT 6
- Malformed @click links crash Textual application HOT 2
- How to link from docs to videos? HOT 2
- Loading Indicator page could use docs about `loading` attribute HOT 1
- Ability to replace text while keeping TextArea history HOT 4
- NoMatches error occurring when changing screens quickly in version 0.49+ HOT 14
- Hidden ListItem in ListView is selected when navigating with keyboard
- `Switch.action_toggle` name clash HOT 1
- Input and TextArea have cursor blinking even though terminal window is not focused HOT 8
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from textual.