Coverage for src/PythonMetaTrader5/legacy/mt5_namespace.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-12 12:29 +0000

1"""The MetaTrader5 namespace, re-exported lazily for 2.x scripts (ADR 0010). 

2 

32.x ran ``from MetaTrader5 import *`` in its ``__init__``, and its own README 

4called ``symbol_info("EURUSD")`` after ``from PythonMetaTrader5 import *``. 

5The package ``__getattr__`` (PEP 562) delegates here, so MetaTrader5 is 

6imported only when one of its names is first used: importing the library, or 

7only its domain types, never depends on the MT5 wheel. 

8""" 

9 

10from __future__ import annotations 

11 

12import warnings 

13from types import ModuleType 

14 

15from PythonMetaTrader5.adapters.mt5_session import import_metatrader5, serialized 

16 

17 

18def public_names() -> list[str]: 

19 module = _module_or_warn() 

20 if module is None: 

21 return [] 

22 return sorted(n for n in dir(module) if not n.startswith("_")) 

23 

24 

25def resolve(name: str) -> object: 

26 """One MT5 name; functions are wrapped to hold the adapter's session lock. 

27 

28 Without the lock a direct ``last_error()`` from a 2.x-style script could run 

29 between the adapter's ``order_send`` and its own ``last_error()`` read, and 

30 a lost order would be reported as "never sent" (ADR 0009). Only names not 

31 defined by the package reach this: a module __getattr__ runs on misses only. 

32 """ 

33 try: 

34 module = None if name.startswith("_") else import_metatrader5() 

35 except ImportError as error: 

36 # AttributeError, not ImportError: hasattr(), getattr(.., default) and 

37 # IDE tooling must keep working on a broken install; the cause is kept. 

38 raise AttributeError(f"PythonMetaTrader5 has no attribute {name!r}: {error}") from error 

39 if module is None or not hasattr(module, name): 

40 raise AttributeError(f"module 'PythonMetaTrader5' has no attribute {name!r}") 

41 value = getattr(module, name) 

42 if callable(value) and not isinstance(value, type): 

43 return serialized(value) 

44 return value 

45 

46 

47def _module_or_warn() -> ModuleType | None: 

48 try: 

49 return import_metatrader5() 

50 except ImportError as error: 

51 # A star import of a broken install keeps our own names (connect() then 

52 # reports the failure as Err) and says loudly why the MT5 names are gone. 

53 # stacklevel 4: past this helper, public_names and the package 

54 # __getattr__, so the warning names the user's import line. 

55 warnings.warn(f"{error}; its names are not re-exported", RuntimeWarning, stacklevel=4) 

56 return None