Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbformat/converter.py: 17%

23 statements  

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

1"""API for converting notebooks between versions.""" 

2 

3# Copyright (c) IPython Development Team. 

4# Distributed under the terms of the Modified BSD License. 

5 

6from . import versions 

7from .reader import get_version 

8from .validator import ValidationError 

9 

10 

11def convert(nb, to_version): 

12 """Convert a notebook node object to a specific version. Assumes that 

13 all the versions starting from 1 to the latest major X are implemented. 

14 In other words, there should never be a case where v1 v2 v3 v5 exist without 

15 a v4. Also assumes that all conversions can be made in one step increments 

16 between major versions and ignores minor revisions. 

17 

18 Parameters 

19 ---------- 

20 nb : NotebookNode 

21 to_version : int 

22 Major revision to convert the notebook to. Can either be an upgrade or 

23 a downgrade. 

24 

25 Raises 

26 ------ 

27 ValueError 

28 Notebook failed to convert. 

29 ValueError 

30 The version specified is invalid or doesn't exist. 

31 ValidationError 

32 Conversion failed due to missing expected attributes. 

33 """ 

34 

35 # Get input notebook version. 

36 (version, version_minor) = get_version(nb) 

37 

38 # Check if destination is target version, if so return contents 

39 if version == to_version: 

40 return nb 

41 

42 # If the version exist, try to convert to it one step at a time. 

43 elif to_version in versions: 

44 # Get the the version that this recursion will convert to as a step 

45 # closer to the final revision. Make sure the newer of the conversion 

46 # functions is used to perform the conversion. 

47 if to_version > version: 

48 step_version = version + 1 

49 convert_function = versions[step_version].upgrade 

50 else: 

51 step_version = version - 1 

52 convert_function = versions[version].downgrade 

53 

54 try: 

55 # Convert and make sure version changed during conversion. 

56 converted = convert_function(nb) 

57 if converted.get("nbformat", 1) == version: 

58 msg = "Failed to convert notebook from v%d to v%d." % (version, step_version) 

59 raise ValueError(msg) 

60 except AttributeError as e: 

61 msg = f"Notebook could not be converted from version {version} to version {step_version} because it's missing a key: {e}" 

62 raise ValidationError(msg) from None 

63 

64 # Recursively convert until target version is reached. 

65 return convert(converted, to_version) 

66 else: 

67 raise ValueError( 

68 "Cannot convert notebook to v%d because that version doesn't exist" % (to_version) 

69 )