|
3 | 3 | import os
|
4 | 4 | from io import StringIO
|
5 | 5 | from pathlib import Path
|
6 |
| -from typing import Union |
| 6 | +from typing import Union, Any |
7 | 7 |
|
8 | 8 | import numpy as np
|
9 | 9 | import pyecospold
|
|
18 | 18 | from tqdm import tqdm
|
19 | 19 |
|
20 | 20 |
|
21 |
| -def robust_text(root: etree.ElementBase, attribute: str): |
| 21 | +def robust_text(root: etree.ElementBase, attribute: str) -> str | None: |
22 | 22 | """Just because the spec says it must be there doesn't mean it will be."""
|
23 | 23 | try:
|
24 | 24 | return getattr(root, attribute).text
|
25 | 25 | except AttributeError:
|
26 | 26 | return None
|
27 | 27 |
|
28 | 28 |
|
| 29 | +def robust_nested_attribute(root: etree.ElementBase, attr1: str, attr2: str) -> Any: |
| 30 | + """Try to get nested attribute, and fail gracefully.""" |
| 31 | + try: |
| 32 | + first_level = getattr(root, attr1) |
| 33 | + if first_level is None: |
| 34 | + return None |
| 35 | + return getattr(first_level, attr2) |
| 36 | + except AttributeError: |
| 37 | + return None |
| 38 | + |
| 39 | + |
29 | 40 | class Ecospold1DataExtractor:
|
30 | 41 | @classmethod
|
31 | 42 | def extract(
|
@@ -131,12 +142,12 @@ def process_dataset(
|
131 | 142 | "technology": "Technology: " + PI.technology.text,
|
132 | 143 | "timePeriod": "Time period: " + PI.timePeriod.text,
|
133 | 144 | "productionVolume": "Production volume: "
|
134 |
| - + (MV.representativeness.productionVolume or ""), |
135 |
| - "sampling": "Sampling: " + (MV.representativeness.samplingProcedure or ""), |
| 145 | + + (robust_nested_attribute(MV, "representativeness", "productionVolume") or ""), |
| 146 | + "sampling": "Sampling: " + (robust_nested_attribute(MV, "representativeness", "samplingProcedure") or ""), |
136 | 147 | "extrapolations": "Extrapolations: "
|
137 |
| - + (MV.representativeness.extrapolations or ""), |
| 148 | + + (robust_nested_attribute(MV, "representativeness", "extrapolations") or ""), |
138 | 149 | "uncertaintyAdjustments": "Uncertainty adjustments: "
|
139 |
| - + (MV.representativeness.uncertaintyAdjustments or ""), |
| 150 | + + (robust_nested_attribute(MV, "representativeness", "uncertaintyAdjustments") or ""), |
140 | 151 | }
|
141 | 152 |
|
142 | 153 | def get_authors():
|
|
0 commit comments