Преглед на файлове

Merge pull request #1266 from zauberzeug/optional-features

Refactor optional feature handling to preserve signature of ui.plotly etc.
Falko Schindler преди 1 година
родител
ревизия
196ad18559
променени са 3 файла, в които са добавени 29 реда и са изтрити 31 реда
  1. 12 2
      nicegui/elements/plotly.py
  2. 11 2
      nicegui/elements/pyplot.py
  3. 6 27
      nicegui/ui.py

+ 12 - 2
nicegui/elements/plotly.py

@@ -1,9 +1,16 @@
-from typing import Dict, Union
+from __future__ import annotations
 
 
-import plotly.graph_objects as go
+from typing import Dict, Union
 
 
+from .. import globals
 from ..element import Element
 from ..element import Element
 
 
+try:
+    import plotly.graph_objects as go
+    globals.optional_features.add('plotly')
+except ImportError:
+    pass
+
 
 
 class Plotly(Element, component='plotly.vue', libraries=['lib/plotly/plotly.min.js']):
 class Plotly(Element, component='plotly.vue', libraries=['lib/plotly/plotly.min.js']):
 
 
@@ -22,6 +29,9 @@ class Plotly(Element, component='plotly.vue', libraries=['lib/plotly/plotly.min.
         :param figure: Plotly figure to be rendered. Can be either a `go.Figure` instance, or
         :param figure: Plotly figure to be rendered. Can be either a `go.Figure` instance, or
                        a `dict` object with keys `data`, `layout`, `config` (optional).
                        a `dict` object with keys `data`, `layout`, `config` (optional).
         """
         """
+        if not 'plotly' in globals.optional_features:
+            raise ImportError('Plotly is not installed. Please run "pip install nicegui[plotly]".')
+
         super().__init__()
         super().__init__()
 
 
         self.figure = figure
         self.figure = figure

+ 11 - 2
nicegui/elements/pyplot.py

@@ -1,12 +1,18 @@
 import asyncio
 import asyncio
 import io
 import io
+import os
 from typing import Any
 from typing import Any
 
 
-import matplotlib.pyplot as plt
-
 from .. import background_tasks, globals
 from .. import background_tasks, globals
 from ..element import Element
 from ..element import Element
 
 
+try:
+    if os.environ.get('MATPLOTLIB', 'true').lower() == 'true':
+        import matplotlib.pyplot as plt
+        globals.optional_features.add('matplotlib')
+except ImportError:
+    pass
+
 
 
 class Pyplot(Element):
 class Pyplot(Element):
 
 
@@ -18,6 +24,9 @@ class Pyplot(Element):
         :param close: whether the figure should be closed after exiting the context; set to `False` if you want to update it later (default: `True`)
         :param close: whether the figure should be closed after exiting the context; set to `False` if you want to update it later (default: `True`)
         :param kwargs: arguments like `figsize` which should be passed to `pyplot.figure <https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html>`_
         :param kwargs: arguments like `figsize` which should be passed to `pyplot.figure <https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html>`_
         """
         """
+        if 'matplotlib' not in globals.optional_features:
+            raise ImportError('Matplotlib is not installed. Please run "pip install matplotlib".')
+
         super().__init__('div')
         super().__init__('div')
         self.close = close
         self.close = close
         self.fig = plt.figure(**kwargs)
         self.fig = plt.figure(**kwargs)

+ 6 - 27
nicegui/ui.py

@@ -1,5 +1,3 @@
-import os
-
 __all__ = [
 __all__ = [
     'deprecated',
     'deprecated',
     'element',
     'element',
@@ -34,6 +32,7 @@ __all__ = [
     'keyboard',
     'keyboard',
     'knob',
     'knob',
     'label',
     'label',
+    'line_plot',
     'link',
     'link',
     'link_target',
     'link_target',
     'log',
     'log',
@@ -42,8 +41,10 @@ __all__ = [
     'menu_item',
     'menu_item',
     'mermaid',
     'mermaid',
     'number',
     'number',
+    'plotly',
     'circular_progress',
     'circular_progress',
     'linear_progress',
     'linear_progress',
+    'pyplot',
     'query',
     'query',
     'radio',
     'radio',
     'row',
     'row',
@@ -124,6 +125,7 @@ from .elements.joystick import Joystick as joystick
 from .elements.keyboard import Keyboard as keyboard
 from .elements.keyboard import Keyboard as keyboard
 from .elements.knob import Knob as knob
 from .elements.knob import Knob as knob
 from .elements.label import Label as label
 from .elements.label import Label as label
+from .elements.line_plot import LinePlot as line_plot
 from .elements.link import Link as link
 from .elements.link import Link as link
 from .elements.link import LinkTarget as link_target
 from .elements.link import LinkTarget as link_target
 from .elements.log import Log as log
 from .elements.log import Log as log
@@ -132,8 +134,10 @@ from .elements.menu import Menu as menu
 from .elements.menu import MenuItem as menu_item
 from .elements.menu import MenuItem as menu_item
 from .elements.mermaid import Mermaid as mermaid
 from .elements.mermaid import Mermaid as mermaid
 from .elements.number import Number as number
 from .elements.number import Number as number
+from .elements.plotly import Plotly as plotly
 from .elements.progress import CircularProgress as circular_progress
 from .elements.progress import CircularProgress as circular_progress
 from .elements.progress import LinearProgress as linear_progress
 from .elements.progress import LinearProgress as linear_progress
+from .elements.pyplot import Pyplot as pyplot
 from .elements.query import query
 from .elements.query import query
 from .elements.radio import Radio as radio
 from .elements.radio import Radio as radio
 from .elements.row import Row as row
 from .elements.row import Row as row
@@ -177,28 +181,3 @@ from .page_layout import PageSticky as page_sticky
 from .page_layout import RightDrawer as right_drawer
 from .page_layout import RightDrawer as right_drawer
 from .run import run
 from .run import run
 from .run_with import run_with
 from .run_with import run_with
-
-try:
-    from .elements.plotly import Plotly as plotly
-    globals.optional_features.add('plotly')
-except ImportError:
-    def plotly(*args, **kwargs):
-        raise ImportError('Plotly is not installed. Please run "pip install plotly".')
-__all__.append('plotly')
-
-if os.environ.get('MATPLOTLIB', 'true').lower() == 'true':
-    try:
-        from .elements.line_plot import LinePlot as line_plot
-        from .elements.pyplot import Pyplot as pyplot
-        plot = deprecated(pyplot, 'ui.plot', 'ui.pyplot', 317)
-        globals.optional_features.add('matplotlib')
-    except ImportError:
-        def line_plot(*args, **kwargs):
-            raise ImportError('Matplotlib is not installed. Please run "pip install matplotlib".')
-
-        def pyplot(*args, **kwargs):
-            raise ImportError('Matplotlib is not installed. Please run "pip install matplotlib".')
-
-        def plot(*args, **kwargs):
-            raise ImportError('Matplotlib is not installed. Please run "pip install matplotlib".')
-    __all__.extend(['line_plot', 'pyplot', 'plot'])