Importing certain python packages gives Errors/Conflicts #111649

Closed
opened 2023-08-29 10:09:45 +02:00 by domef · 3 comments

System Information
Operating system: Ubuntu 22.04.3 LTS
Graphics card: GeForce RTX 2080 Ti

Blender Version
Broken: bpy 3.6.0
Worked: none

Short description of error

When in the same file bpy and other particular packages (e.g. pyvista, textual.widgets) are imported errors are raised at the end of the execution.

Exact steps for others to reproduce the error

For example, with textual.widgets:

import bpy
import textual.widgets

print("Hello, World!")

This error is raised:

Hello, World!
Exception ignored in atexit callback: <function disable_all at 0x7fd64b3e1c60>
Traceback (most recent call last):
  File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 478, in disable_all
    addon_modules = [
  File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 480, in <listcomp>
    if getattr(item[1], "__addon_enabled__", False)
  File "/home/federico/venv/lib/python3.10/site-packages/textual/widgets/__init__.py", line 94, in __getattr__
    raise ImportError(f"Package 'textual.widgets' has no class '{widget_class}'")
ImportError: Package 'textual.widgets' has no class '__addon_enabled__'

I managed to fixed it:

import importlib
import traceback
import typing as t
from types import ModuleType

import bpy
import textual.widgets


def monkeypatch_module_getattr(
    module: t.Union[str, t.Type[ModuleType]], debug: bool = False, default: t.Any = None
):
    if isinstance(module, str):
        module = importlib.import_module(module)
    old_getattr = module.__getattr__

    def new_getattr(key: str):
        try:
            return old_getattr(key)
        except Exception:
            if debug:
                traceback.print_exc()
            return default

    if module.__getattr__ is not new_getattr:
        module.__getattr__ = new_getattr


monkeypatch_module_getattr(textual.widgets)
print("Hello, World!")

The output is:

Hello, World!

But with pyvista

import bpy
import pyvista

print("Hello, World!")

This error is raised and my previous fix doesn't work anymore:

Hello, World!
Exception ignored in atexit callback: <function disable_all at 0x7f0c843e1c60>
Traceback (most recent call last):
  File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 478, in disable_all
    addon_modules = [
  File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 478, in <listcomp>
    addon_modules = [
RuntimeError: dictionary changed size during iteration

Inspecting the bpy code, this is the code for disable_all:

def disable_all():
    import sys
    # Collect modules to disable first because dict can be modified as we disable.
    addon_modules = [
        item for item in sys.modules.items()
        if getattr(item[1], "__addon_enabled__", False)
    ]
    # Check the enabled state again since it's possible the disable call
    # of one add-on disables others.
    for mod_name, mod in addon_modules:
        if getattr(mod, "__addon_enabled__", False):
            disable(mod_name)

Changing it fixes this last error but I don't know if it's correct:

def disable_all():
    import sys
    # Collect modules to disable first because dict can be modified as we disable.
    modules = {k:v for k,v in sys.modules.items()}
    addon_modules = [
        item for item in modules
        if getattr(item[1], "__addon_enabled__", False)
    ]
    # Check the enabled state again since it's possible the disable call
    # of one add-on disables others.
    for mod_name, mod in addon_modules:
        if getattr(mod, "__addon_enabled__", False):
            disable(mod_name)

I also paste here the __getattr__ of textual.widgets and pyvista for the sake of completeness:

def __getattr__(widget_class: str) -> type[Widget]:
    try:
        return _WIDGETS_LAZY_LOADING_CACHE[widget_class]
    except KeyError:
        pass

    if widget_class not in __all__:
        raise ImportError(f"Package 'textual.widgets' has no class '{widget_class}'")

    widget_module_path = f"._{camel_to_snake(widget_class)}"
    module = import_module(widget_module_path, package="textual.widgets")
    class_ = getattr(module, widget_class)

    _WIDGETS_LAZY_LOADING_CACHE[widget_class] = class_
    return class_
def __getattr__(name):
    """Fetch an attribute ``name`` from ``globals()`` or the ``pyvista.plotting`` module.

    This override is implemented to prevent importing all of the plotting module
    and GL-dependent VTK modules when importing PyVista.

    Raises
    ------
    AttributeError
        If the attribute is not found.

    """
    import importlib
    import inspect

    allow = {
        'demos',
        'examples',
        'ext',
        'trame',
        'utilities',
    }
    if name in allow:
        return importlib.import_module(f'pyvista.{name}')

    # avoid recursive import
    if 'pyvista.plotting' not in sys.modules:
        import pyvista.plotting

    try:
        feature = inspect.getattr_static(sys.modules['pyvista.plotting'], name)
    except AttributeError as e:
        raise AttributeError(f"module 'pyvista' has no attribute '{name}'") from None

    return feature
**System Information** Operating system: Ubuntu 22.04.3 LTS Graphics card: GeForce RTX 2080 Ti **Blender Version** Broken: bpy 3.6.0 Worked: none **Short description of error** When in the same file `bpy` and other particular packages (e.g. `pyvista`, `textual.widgets`) are imported errors are raised at the end of the execution. **Exact steps for others to reproduce the error** For example, with `textual.widgets`: ```python import bpy import textual.widgets print("Hello, World!") ``` This error is raised: ``` Hello, World! Exception ignored in atexit callback: <function disable_all at 0x7fd64b3e1c60> Traceback (most recent call last): File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 478, in disable_all addon_modules = [ File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 480, in <listcomp> if getattr(item[1], "__addon_enabled__", False) File "/home/federico/venv/lib/python3.10/site-packages/textual/widgets/__init__.py", line 94, in __getattr__ raise ImportError(f"Package 'textual.widgets' has no class '{widget_class}'") ImportError: Package 'textual.widgets' has no class '__addon_enabled__' ``` I managed to fixed it: ```python import importlib import traceback import typing as t from types import ModuleType import bpy import textual.widgets def monkeypatch_module_getattr( module: t.Union[str, t.Type[ModuleType]], debug: bool = False, default: t.Any = None ): if isinstance(module, str): module = importlib.import_module(module) old_getattr = module.__getattr__ def new_getattr(key: str): try: return old_getattr(key) except Exception: if debug: traceback.print_exc() return default if module.__getattr__ is not new_getattr: module.__getattr__ = new_getattr monkeypatch_module_getattr(textual.widgets) print("Hello, World!") ``` The output is: ``` Hello, World! ``` But with `pyvista` ```python import bpy import pyvista print("Hello, World!") ``` This error is raised and my previous fix doesn't work anymore: ``` Hello, World! Exception ignored in atexit callback: <function disable_all at 0x7f0c843e1c60> Traceback (most recent call last): File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 478, in disable_all addon_modules = [ File "/home/federico/venv/lib/python3.10/site-packages/bpy/3.6/scripts/modules/addon_utils.py", line 478, in <listcomp> addon_modules = [ RuntimeError: dictionary changed size during iteration ``` Inspecting the bpy code, this is the code for `disable_all`: ```python def disable_all(): import sys # Collect modules to disable first because dict can be modified as we disable. addon_modules = [ item for item in sys.modules.items() if getattr(item[1], "__addon_enabled__", False) ] # Check the enabled state again since it's possible the disable call # of one add-on disables others. for mod_name, mod in addon_modules: if getattr(mod, "__addon_enabled__", False): disable(mod_name) ``` Changing it fixes this last error but I don't know if it's correct: ```python def disable_all(): import sys # Collect modules to disable first because dict can be modified as we disable. modules = {k:v for k,v in sys.modules.items()} addon_modules = [ item for item in modules if getattr(item[1], "__addon_enabled__", False) ] # Check the enabled state again since it's possible the disable call # of one add-on disables others. for mod_name, mod in addon_modules: if getattr(mod, "__addon_enabled__", False): disable(mod_name) ``` I also paste here the `__getattr__` of `textual.widgets` and `pyvista` for the sake of completeness: ```python def __getattr__(widget_class: str) -> type[Widget]: try: return _WIDGETS_LAZY_LOADING_CACHE[widget_class] except KeyError: pass if widget_class not in __all__: raise ImportError(f"Package 'textual.widgets' has no class '{widget_class}'") widget_module_path = f"._{camel_to_snake(widget_class)}" module = import_module(widget_module_path, package="textual.widgets") class_ = getattr(module, widget_class) _WIDGETS_LAZY_LOADING_CACHE[widget_class] = class_ return class_ ``` ```python def __getattr__(name): """Fetch an attribute ``name`` from ``globals()`` or the ``pyvista.plotting`` module. This override is implemented to prevent importing all of the plotting module and GL-dependent VTK modules when importing PyVista. Raises ------ AttributeError If the attribute is not found. """ import importlib import inspect allow = { 'demos', 'examples', 'ext', 'trame', 'utilities', } if name in allow: return importlib.import_module(f'pyvista.{name}') # avoid recursive import if 'pyvista.plotting' not in sys.modules: import pyvista.plotting try: feature = inspect.getattr_static(sys.modules['pyvista.plotting'], name) except AttributeError as e: raise AttributeError(f"module 'pyvista' has no attribute '{name}'") from None return feature ```
domef added the
Priority
Normal
Type
Report
Status
Needs Triage
labels 2023-08-29 10:09:46 +02:00
Iliya Katushenock added the
Interest
Python API
label 2023-08-29 13:46:32 +02:00
Philipp Oeser changed title from Errors/Conflicts with other packages to Importing certain python packages gives Errors/Conflicts 2023-08-29 14:40:38 +02:00

Thank you for bringing this to our attention, @Federico-Domeniconi.

It seems that when importing certain packages like textual.widgets and pyvista, Blender raises some erros when closing.
The errors are related to conflicts between these packages and the addon_utils module.

You also provided some suggested fixes. Note that for code review, you can also submit Pull Requests: https://wiki.blender.org/wiki/Process/Contributing_Code
The development team will review your report and work towards resolving the issue.

I can confirm the problem (I had to pip install textual) so I will forward it to the Python API team.

Thank you for bringing this to our attention, @Federico-Domeniconi. It seems that when importing certain packages like `textual.widgets` and `pyvista`, Blender raises some erros when closing. The errors are related to conflicts between these packages and the `addon_utils` module. You also provided some suggested fixes. Note that for code review, you can also submit Pull Requests: https://wiki.blender.org/wiki/Process/Contributing_Code The development team will review your report and work towards resolving the issue. I can confirm the problem (I had to `pip install textual`) so I will forward it to the `Python API` team.
Germano Cavalcante added
Module
Python API
Status
Confirmed
and removed
Status
Needs Triage
Interest
Python API
labels 2023-08-29 19:09:39 +02:00

@Federico-Domeniconi If you propose change here, I guess you could have created a pull request. As for correctness I would ask @ideasman42.

@Federico-Domeniconi If you propose change here, I guess you could have created a pull request. As for correctness I would ask @ideasman42.
Member
@ideasman42 ^
Blender Bot added
Status
Resolved
and removed
Status
Confirmed
labels 2023-08-30 08:16:57 +02:00
Sign in to join this conversation.
No Label
Interest
Alembic
Interest
Animation & Rigging
Interest
Asset Browser
Interest
Asset Browser Project Overview
Interest
Audio
Interest
Automated Testing
Interest
Blender Asset Bundle
Interest
BlendFile
Interest
Collada
Interest
Compatibility
Interest
Compositing
Interest
Core
Interest
Cycles
Interest
Dependency Graph
Interest
Development Management
Interest
EEVEE
Interest
EEVEE & Viewport
Interest
Freestyle
Interest
Geometry Nodes
Interest
Grease Pencil
Interest
ID Management
Interest
Images & Movies
Interest
Import Export
Interest
Line Art
Interest
Masking
Interest
Metal
Interest
Modeling
Interest
Modifiers
Interest
Motion Tracking
Interest
Nodes & Physics
Interest
OpenGL
Interest
Overlay
Interest
Overrides
Interest
Performance
Interest
Physics
Interest
Pipeline, Assets & IO
Interest
Platforms, Builds & Tests
Interest
Python API
Interest
Render & Cycles
Interest
Render Pipeline
Interest
Sculpt, Paint & Texture
Interest
Text Editor
Interest
Translations
Interest
Triaging
Interest
Undo
Interest
USD
Interest
User Interface
Interest
UV Editing
Interest
VFX & Video
Interest
Video Sequencer
Interest
Virtual Reality
Interest
Vulkan
Interest
Wayland
Interest
Workbench
Interest: X11
Legacy
Blender 2.8 Project
Legacy
Milestone 1: Basic, Local Asset Browser
Legacy
OpenGL Error
Meta
Good First Issue
Meta
Papercut
Meta
Retrospective
Meta
Security
Module
Animation & Rigging
Module
Core
Module
Development Management
Module
EEVEE & Viewport
Module
Grease Pencil
Module
Modeling
Module
Nodes & Physics
Module
Pipeline, Assets & IO
Module
Platforms, Builds & Tests
Module
Python API
Module
Render & Cycles
Module
Sculpt, Paint & Texture
Module
Triaging
Module
User Interface
Module
VFX & Video
Platform
FreeBSD
Platform
Linux
Platform
macOS
Platform
Windows
Priority
High
Priority
Low
Priority
Normal
Priority
Unbreak Now!
Status
Archived
Status
Confirmed
Status
Duplicate
Status
Needs Info from Developers
Status
Needs Information from User
Status
Needs Triage
Status
Resolved
Type
Bug
Type
Design
Type
Known Issue
Type
Patch
Type
Report
Type
To Do
No Milestone
No project
No Assignees
4 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: blender/blender#111649
No description provided.