Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/airflow/utils/module_loading.py: 48%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

29 statements  

1# 

2# Licensed to the Apache Software Foundation (ASF) under one 

3# or more contributor license agreements. See the NOTICE file 

4# distributed with this work for additional information 

5# regarding copyright ownership. The ASF licenses this file 

6# to you under the Apache License, Version 2.0 (the 

7# "License"); you may not use this file except in compliance 

8# with the License. You may obtain a copy of the License at 

9# 

10# http://www.apache.org/licenses/LICENSE-2.0 

11# 

12# Unless required by applicable law or agreed to in writing, 

13# software distributed under the License is distributed on an 

14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 

15# KIND, either express or implied. See the License for the 

16# specific language governing permissions and limitations 

17# under the License. 

18from __future__ import annotations 

19 

20import pkgutil 

21from importlib import import_module 

22from typing import TYPE_CHECKING, Callable 

23 

24if TYPE_CHECKING: 

25 from types import ModuleType 

26 

27 

28def import_string(dotted_path: str): 

29 """ 

30 Import a dotted module path and return the attribute/class designated by the last name in the path. 

31 

32 Raise ImportError if the import failed. 

33 """ 

34 try: 

35 module_path, class_name = dotted_path.rsplit(".", 1) 

36 except ValueError: 

37 raise ImportError(f"{dotted_path} doesn't look like a module path") 

38 

39 module = import_module(module_path) 

40 

41 try: 

42 return getattr(module, class_name) 

43 except AttributeError: 

44 raise ImportError(f'Module "{module_path}" does not define a "{class_name}" attribute/class') 

45 

46 

47def qualname(o: object | Callable) -> str: 

48 """Convert an attribute/class/function to a string importable by ``import_string``.""" 

49 if callable(o) and hasattr(o, "__module__") and hasattr(o, "__name__"): 

50 return f"{o.__module__}.{o.__name__}" 

51 

52 cls = o 

53 

54 if not isinstance(cls, type): # instance or class 

55 cls = type(cls) 

56 

57 name = cls.__qualname__ 

58 module = cls.__module__ 

59 

60 if module and module != "__builtin__": 

61 return f"{module}.{name}" 

62 

63 return name 

64 

65 

66def iter_namespace(ns: ModuleType): 

67 return pkgutil.iter_modules(ns.__path__, ns.__name__ + ".")