Skip to content

Commit

Permalink
[compat_utils] Simplify EnhancedModule
Browse files Browse the repository at this point in the history
  • Loading branch information
pukkandan committed Feb 8, 2023
1 parent acb1042 commit 768a001
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
18 changes: 2 additions & 16 deletions yt_dlp/compat/compat_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,6 @@ def _is_dunder(name):


class EnhancedModule(types.ModuleType):
def __new__(cls, name, *args, **kwargs):
if name not in sys.modules:
return super().__new__(cls, name, *args, **kwargs)

assert not args and not kwargs, 'Cannot pass additional arguments to an existing module'
module = sys.modules[name]
module.__class__ = cls
return module

def __init__(self, name, *args, **kwargs):
# Prevent __new__ from trigerring __init__ again
if name not in sys.modules:
super().__init__(name, *args, **kwargs)

def __bool__(self):
return vars(self).get('__bool__', lambda: True)()

Expand All @@ -60,8 +46,6 @@ def __getattribute__(self, attr):

def passthrough_module(parent, child, allowed_attributes=(..., ), *, callback=lambda _: None):
"""Passthrough parent module into a child module, creating the parent if necessary"""
parent = EnhancedModule(parent)

def __getattr__(attr):
if _is_package(parent):
with contextlib.suppress(ImportError):
Expand Down Expand Up @@ -93,5 +77,7 @@ def from_child(attr):

return _NO_ATTRIBUTE

parent = sys.modules.get(parent, types.ModuleType(parent))
parent.__class__ = EnhancedModule
parent.__getattr__ = __getattr__
return parent
8 changes: 5 additions & 3 deletions yt_dlp/dependencies/Cryptodome.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import types

from ..compat import functools
from ..compat.compat_utils import EnhancedModule, passthrough_module
from ..compat.compat_utils import passthrough_module

try:
import Cryptodome as _parent
except ImportError:
try:
import Crypto as _parent
except (ImportError, SyntaxError): # Old Crypto gives SyntaxError in newer Python
_parent = EnhancedModule('Cryptodome')
_parent = types.ModuleType('no_Cryptodome')
__bool__ = lambda: False

passthrough_module(__name__, _parent, (..., '__version__'))
del passthrough_module, EnhancedModule
del passthrough_module


@property
Expand Down

0 comments on commit 768a001

Please sign in to comment.