Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/build/lib/airflow/utils/module_loading.py: 50%

28 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:35 +0000

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 types import ModuleType 

23from typing import Callable 

24 

25 

26def import_string(dotted_path: str): 

27 """ 

28 Import a dotted module path and return the attribute/class designated by the 

29 last name in the path. Raise ImportError if the import failed. 

30 """ 

31 try: 

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

33 except ValueError: 

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

35 

36 module = import_module(module_path) 

37 

38 try: 

39 return getattr(module, class_name) 

40 except AttributeError: 

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

42 

43 

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

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

46 if callable(o): 

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

48 

49 cls = o 

50 

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

52 cls = type(cls) 

53 

54 name = cls.__qualname__ 

55 module = cls.__module__ 

56 

57 if module and module != "__builtin__": 

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

59 

60 return name 

61 

62 

63def iter_namespace(ns: ModuleType): 

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