utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from datetime import datetime, timedelta, timezone
  13. from dataclasses import is_dataclass, asdict
  14. from collections import OrderedDict
  15. from openleadr import enums
  16. from random import randint
  17. import asyncio
  18. import itertools
  19. import re
  20. import ssl
  21. import hashlib
  22. import uuid
  23. import logging
  24. logger = logging.getLogger('openleadr')
  25. DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
  26. DATETIME_FORMAT_NO_MICROSECONDS = "%Y-%m-%dT%H:%M:%SZ"
  27. def generate_id(*args, **kwargs):
  28. """
  29. Generate a string that can be used as an identifier in OpenADR messages.
  30. """
  31. return str(uuid.uuid4())
  32. def indent_xml(message):
  33. """
  34. Indents the XML in a nice way.
  35. """
  36. INDENT_SIZE = 2
  37. lines = [line.strip() for line in message.split("\n") if line.strip() != ""]
  38. indent = 0
  39. for i, line in enumerate(lines):
  40. if i == 0:
  41. continue
  42. if re.search(r'^</[^>]+>$', line):
  43. indent = indent - INDENT_SIZE
  44. lines[i] = " " * indent + line
  45. if not (re.search(r'</[^>]+>$', line) or line.endswith("/>")):
  46. indent = indent + INDENT_SIZE
  47. return "\n".join(lines)
  48. def flatten_xml(message):
  49. """
  50. Flatten the entire XML structure.
  51. """
  52. lines = [line.strip() for line in message.split("\n") if line.strip() != ""]
  53. for line in lines:
  54. line = re.sub(r'\n', '', line)
  55. line = re.sub(r'\s\s+', ' ', line)
  56. return "".join(lines)
  57. def normalize_dict(ordered_dict):
  58. """
  59. Main conversion function for the output of xmltodict to the OpenLEADR
  60. representation of OpenADR contents.
  61. :param ordered_dict dict: The OrderedDict, dict or dataclass that you wish to convert.
  62. """
  63. if is_dataclass(ordered_dict):
  64. ordered_dict = asdict(ordered_dict)
  65. def normalize_key(key):
  66. if key.startswith('oadr'):
  67. key = key[4:]
  68. elif key.startswith('ei'):
  69. key = key[2:]
  70. # Don't normalize the measurement descriptions
  71. if key in enums._MEASUREMENT_NAMESPACES:
  72. return key
  73. key = re.sub(r'([a-z])([A-Z])', r'\1_\2', key)
  74. if '-' in key:
  75. key = key.replace('-', '_')
  76. return key.lower()
  77. d = {}
  78. for key, value in ordered_dict.items():
  79. # Interpret values from the dict
  80. if key.startswith("@"):
  81. continue
  82. key = normalize_key(key)
  83. if isinstance(value, (OrderedDict, dict)):
  84. d[key] = normalize_dict(value)
  85. elif isinstance(value, list):
  86. d[key] = []
  87. for item in value:
  88. if isinstance(item, (OrderedDict, dict)):
  89. dict_item = normalize_dict(item)
  90. d[key].append(normalize_dict(dict_item))
  91. else:
  92. d[key].append(item)
  93. elif key in ("duration", "startafter", "max_period", "min_period"):
  94. d[key] = parse_duration(value)
  95. elif ("date_time" in key or key == "dtstart") and isinstance(value, str):
  96. d[key] = parse_datetime(value)
  97. elif value in ('true', 'false'):
  98. d[key] = parse_boolean(value)
  99. elif isinstance(value, str):
  100. if re.match(r'^-?\d+$', value):
  101. d[key] = int(value)
  102. elif re.match(r'^-?[\d.]+$', value):
  103. d[key] = float(value)
  104. else:
  105. d[key] = value
  106. else:
  107. d[key] = value
  108. # Do our best to make the dictionary structure as pythonic as possible
  109. if key.startswith("x_ei_"):
  110. d[key[5:]] = d.pop(key)
  111. key = key[5:]
  112. # Group all targets as a list of dicts under the key "target"
  113. if key == 'target':
  114. targets = d.pop(key)
  115. new_targets = []
  116. if targets:
  117. for ikey in targets:
  118. if isinstance(targets[ikey], list):
  119. new_targets.extend([{ikey: value} for value in targets[ikey]])
  120. else:
  121. new_targets.append({ikey: targets[ikey]})
  122. d[key + "s"] = new_targets
  123. key = key + "s"
  124. # Also add a targets_by_type element to this dict
  125. # to access the targets in a more convenient way.
  126. d['targets_by_type'] = group_targets_by_type(new_targets)
  127. # Group all reports as a list of dicts under the key "pending_reports"
  128. if key == "pending_reports":
  129. if isinstance(d[key], dict) and 'report_request_id' in d[key] \
  130. and isinstance(d[key]['report_request_id'], list):
  131. d['pending_reports'] = [{'request_id': rrid}
  132. for rrid in d['pending_reports']['report_request_id']]
  133. # Group all events al a list of dicts under the key "events"
  134. elif key == "event" and isinstance(d[key], list):
  135. events = d.pop("event")
  136. new_events = []
  137. for event in events:
  138. new_event = event['event']
  139. new_event['response_required'] = event['response_required']
  140. new_events.append(new_event)
  141. d["events"] = new_events
  142. # If there's only one event, also put it into a list
  143. elif key == "event" and isinstance(d[key], dict) and "event" in d[key]:
  144. oadr_event = d.pop('event')
  145. ei_event = oadr_event['event']
  146. ei_event['response_required'] = oadr_event['response_required']
  147. d['events'] = [ei_event]
  148. elif key in ("request_event", "created_event") and isinstance(d[key], dict):
  149. d = d[key]
  150. # Plurarize some lists
  151. elif key in ('report_request', 'report', 'specifier_payload'):
  152. if isinstance(d[key], list):
  153. d[key + 's'] = d.pop(key)
  154. else:
  155. d[key + 's'] = [d.pop(key)]
  156. elif key in ('report_description', 'event_signal'):
  157. descriptions = d.pop(key)
  158. if not isinstance(descriptions, list):
  159. descriptions = [descriptions]
  160. for description in descriptions:
  161. # We want to make the identification of the measurement universal
  162. for measurement in enums._MEASUREMENT_NAMESPACES:
  163. if measurement in description:
  164. name, item = measurement, description.pop(measurement)
  165. break
  166. else:
  167. break
  168. item['description'] = item.pop('item_description', None)
  169. item['unit'] = item.pop('item_units', None)
  170. if 'si_scale_code' in item:
  171. item['scale'] = item.pop('si_scale_code')
  172. if 'pulse_factor' in item:
  173. item['pulse_factor'] = item.pop('pulse_factor')
  174. description['measurement'] = {'name': name,
  175. **item}
  176. d[key + 's'] = descriptions
  177. # Promote the contents of the Qualified Event ID
  178. elif key == "qualified_event_id" and isinstance(d['qualified_event_id'], dict):
  179. qeid = d.pop('qualified_event_id')
  180. d['event_id'] = qeid['event_id']
  181. d['modification_number'] = qeid['modification_number']
  182. # Durations are encapsulated in their own object, remove this nesting
  183. elif isinstance(d[key], dict) and "duration" in d[key] and len(d[key]) == 1:
  184. d[key] = d[key]["duration"]
  185. # In general, remove all double nesting
  186. elif isinstance(d[key], dict) and key in d[key] and len(d[key]) == 1:
  187. d[key] = d[key][key]
  188. # In general, remove the double nesting of lists of items
  189. elif isinstance(d[key], dict) and key[:-1] in d[key] and len(d[key]) == 1:
  190. if isinstance(d[key][key[:-1]], list):
  191. d[key] = d[key][key[:-1]]
  192. else:
  193. d[key] = [d[key][key[:-1]]]
  194. # Payload values are wrapped in an object according to their type. We don't need that.
  195. elif key in ("signal_payload", "current_value"):
  196. value = d[key]
  197. if isinstance(d[key], dict):
  198. if 'payload_float' in d[key] and 'value' in d[key]['payload_float'] \
  199. and d[key]['payload_float']['value'] is not None:
  200. d[key] = float(d[key]['payload_float']['value'])
  201. elif 'payload_int' in d[key] and 'value' in d[key]['payload_int'] \
  202. and d[key]['payload_int'] is not None:
  203. d[key] = int(d[key]['payload_int']['value'])
  204. # Report payloads contain an r_id and a type-wrapped payload_float
  205. elif key == 'report_payload':
  206. if 'payload_float' in d[key] and 'value' in d[key]['payload_float']:
  207. v = d[key].pop('payload_float')
  208. d[key]['value'] = float(v['value'])
  209. elif 'payload_int' in d[key] and 'value' in d[key]['payload_int']:
  210. v = d[key].pop('payload_float')
  211. d[key]['value'] = int(v['value'])
  212. # All values other than 'false' must be interpreted as True for testEvent (rule 006)
  213. elif key == 'test_event' and not isinstance(d[key], bool):
  214. d[key] = True
  215. # Promote the 'text' item
  216. elif isinstance(d[key], dict) and "text" in d[key] and len(d[key]) == 1:
  217. if key == 'uid':
  218. d[key] = int(d[key]["text"])
  219. else:
  220. d[key] = d[key]["text"]
  221. # Promote a 'date-time' item
  222. elif isinstance(d[key], dict) and "date_time" in d[key] and len(d[key]) == 1:
  223. d[key] = d[key]["date_time"]
  224. # Promote 'properties' item, discard the unused? 'components' item
  225. elif isinstance(d[key], dict) and "properties" in d[key] and len(d[key]) <= 2:
  226. d[key] = d[key]["properties"]
  227. # Remove all empty dicts
  228. elif isinstance(d[key], dict) and len(d[key]) == 0:
  229. d.pop(key)
  230. return d
  231. def parse_datetime(value):
  232. """
  233. Parse an ISO8601 datetime into a datetime.datetime object.
  234. """
  235. matches = re.match(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.?(\d{1,6})?\d*Z', value)
  236. if matches:
  237. year, month, day, hour, minute, second, micro = (int(value) for value in matches.groups())
  238. return datetime(year, month, day, hour, minute, second, micro, tzinfo=timezone.utc)
  239. else:
  240. logger.warning(f"parse_datetime: {value} did not match format")
  241. return value
  242. def parse_duration(value):
  243. """
  244. Parse a RFC5545 duration.
  245. """
  246. # TODO: implement the full regex:
  247. # matches = re.match(r'(\+|\-)?P((\d+Y)?(\d+M)?(\d+D)?T?(\d+H)?(\d+M)?(\d+S)?)|(\d+W)', value)
  248. if isinstance(value, timedelta):
  249. return value
  250. matches = re.match(r'P(\d+(?:D|W))?T?(\d+H)?(\d+M)?(\d+S)?', value)
  251. if not matches:
  252. return False
  253. days = hours = minutes = seconds = 0
  254. _days, _hours, _minutes, _seconds = matches.groups()
  255. if _days:
  256. if _days.endswith("D"):
  257. days = int(_days[:-1])
  258. elif _days.endswith("W"):
  259. days = int(_days[:-1]) * 7
  260. if _hours:
  261. hours = int(_hours[:-1])
  262. if _minutes:
  263. minutes = int(_minutes[:-1])
  264. if _seconds:
  265. seconds = int(_seconds[:-1])
  266. return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  267. def parse_boolean(value):
  268. if value == 'true':
  269. return True
  270. else:
  271. return False
  272. def peek(iterable):
  273. """
  274. Peek into an iterable.
  275. """
  276. try:
  277. first = next(iterable)
  278. except StopIteration:
  279. return None
  280. else:
  281. return itertools.chain([first], iterable)
  282. def datetimeformat(value, format=DATETIME_FORMAT):
  283. """
  284. Format a given datetime as a UTC ISO3339 string.
  285. """
  286. if not isinstance(value, datetime):
  287. return value
  288. return value.astimezone(timezone.utc).strftime(format)
  289. def timedeltaformat(value):
  290. """
  291. Format a timedelta to a RFC5545 Duration.
  292. """
  293. if not isinstance(value, timedelta):
  294. return value
  295. days = value.days
  296. hours, seconds = divmod(value.seconds, 3600)
  297. minutes, seconds = divmod(seconds, 60)
  298. formatted = "P"
  299. if days:
  300. formatted += f"{days}D"
  301. if hours or minutes or seconds:
  302. formatted += "T"
  303. if hours:
  304. formatted += f"{hours}H"
  305. if minutes:
  306. formatted += f"{minutes}M"
  307. if seconds:
  308. formatted += f"{seconds}S"
  309. return formatted
  310. def booleanformat(value):
  311. """
  312. Format a boolean value
  313. """
  314. if isinstance(value, bool):
  315. if value is True:
  316. return "true"
  317. elif value is False:
  318. return "false"
  319. elif value in ("true", "false"):
  320. return value
  321. else:
  322. raise ValueError(f"A boolean value must be provided, not {value}.")
  323. def ensure_bytes(obj):
  324. """
  325. Converts a utf-8 str object to bytes.
  326. """
  327. if obj is None:
  328. return obj
  329. if isinstance(obj, bytes):
  330. return obj
  331. if isinstance(obj, str):
  332. return bytes(obj, 'utf-8')
  333. else:
  334. raise TypeError("Must be bytes or str")
  335. def ensure_str(obj):
  336. """
  337. Converts bytes to a utf-8 string.
  338. """
  339. if obj is None:
  340. return None
  341. if isinstance(obj, str):
  342. return obj
  343. if isinstance(obj, bytes):
  344. return obj.decode('utf-8')
  345. else:
  346. raise TypeError("Must be bytes or str")
  347. def certificate_fingerprint_from_der(der_bytes):
  348. hash = hashlib.sha256(der_bytes).digest().hex()
  349. return ":".join([hash[i-2:i].upper() for i in range(-20, 0, 2)])
  350. def certificate_fingerprint(certificate_str):
  351. """
  352. Calculate the fingerprint for the given certificate, as defined by OpenADR.
  353. """
  354. der_bytes = ssl.PEM_cert_to_DER_cert(ensure_str(certificate_str))
  355. return certificate_fingerprint_from_der(der_bytes)
  356. def extract_pem_cert(tree):
  357. """
  358. Extract a given X509 certificate inside an XML tree and return the standard
  359. form of a PEM-encoded certificate.
  360. :param tree lxml.etree: The tree that contains the X509 element. This is
  361. usually the KeyInfo element from the XMLDsig Signature
  362. part of the message.
  363. """
  364. cert = tree.find('.//{http://www.w3.org/2000/09/xmldsig#}X509Certificate').text
  365. return "-----BEGIN CERTIFICATE-----\n" + cert + "-----END CERTIFICATE-----\n"
  366. def find_by(dict_or_list, key, value, *args):
  367. """
  368. Find a dict inside a dict or list by key, value properties.
  369. """
  370. search_params = [(key, value)]
  371. if args:
  372. search_params += [(args[i], args[i+1]) for i in range(0, len(args), 2)]
  373. if isinstance(dict_or_list, dict):
  374. dict_or_list = dict_or_list.values()
  375. for item in dict_or_list:
  376. if not isinstance(item, dict):
  377. _item = item.__dict__
  378. else:
  379. _item = item
  380. for key, value in search_params:
  381. if isinstance(value, tuple):
  382. if _item[key] not in value:
  383. break
  384. else:
  385. if _item[key] != value:
  386. break
  387. else:
  388. return item
  389. else:
  390. return None
  391. def group_by(list_, key, pop_key=False):
  392. """
  393. Return a dict that groups values
  394. """
  395. grouped = {}
  396. key_path = key.split(".")
  397. for item in list_:
  398. value = item
  399. for key in key_path:
  400. value = value.get(key)
  401. if value not in grouped:
  402. grouped[value] = []
  403. grouped[value].append(item)
  404. return grouped
  405. def cron_config(interval, randomize_seconds=False):
  406. """
  407. Returns a dict with cron settings for the given interval
  408. """
  409. if randomize_seconds:
  410. seconds_offset = min(60, randint(0, interval.total_seconds()))
  411. else:
  412. seconds_offset = "*"
  413. if interval < timedelta(minutes=1):
  414. second = f"{seconds_offset}/{interval.seconds}"
  415. minute = "*"
  416. hour = "*"
  417. elif interval < timedelta(hours=1):
  418. second = f"{seconds_offset}" if randomize_seconds else "0"
  419. minute = f"*/{int(interval.total_seconds()/60)}"
  420. hour = "*"
  421. elif interval < timedelta(hours=24):
  422. second = f"{seconds_offset}" if randomize_seconds else "0"
  423. minute = "0"
  424. hour = f"*/{int(interval.total_seconds()/3600)}"
  425. else:
  426. second = f"{seconds_offset}" if randomize_seconds else "0"
  427. minute = "0"
  428. hour = "0"
  429. return {"second": second, "minute": minute, "hour": hour}
  430. def get_cert_fingerprint_from_request(request):
  431. ssl_object = request.transport.get_extra_info('ssl_object')
  432. if ssl_object:
  433. der_bytes = ssl_object.getpeercert(binary_form=True)
  434. if der_bytes:
  435. return certificate_fingerprint_from_der(der_bytes)
  436. def get_certificate_common_name(request):
  437. cert = request.transport.get_extra_info('peercert')
  438. if cert:
  439. subject = dict(x[0] for x in cert['subject'])
  440. return subject.get('commonName')
  441. def group_targets_by_type(list_of_targets):
  442. targets_by_type = {}
  443. for target in list_of_targets:
  444. for key, value in target.items():
  445. if value is None:
  446. continue
  447. if key not in targets_by_type:
  448. targets_by_type[key] = []
  449. targets_by_type[key].append(value)
  450. return targets_by_type
  451. def ungroup_targets_by_type(targets_by_type):
  452. ungrouped_targets = []
  453. for target_type, targets in targets_by_type.items():
  454. if isinstance(targets, list):
  455. for target in targets:
  456. ungrouped_targets.append({target_type: target})
  457. elif isinstance(targets, str):
  458. ungrouped_targets.append({target_type: targets})
  459. return ungrouped_targets
  460. def validate_report_measurement_dict(measurement):
  461. from openleadr.enums import _ACCEPTABLE_UNITS, _MEASUREMENT_DESCRIPTIONS
  462. if 'name' not in measurement \
  463. or 'description' not in measurement \
  464. or 'unit' not in measurement:
  465. raise ValueError("The measurement dict must contain the following keys: "
  466. "'name', 'description', 'unit'. Please correct this.")
  467. name = measurement['name']
  468. description = measurement['description']
  469. unit = measurement['unit']
  470. # Validate the item name and description match
  471. if name in _MEASUREMENT_DESCRIPTIONS:
  472. required_description = _MEASUREMENT_DESCRIPTIONS[name]
  473. if description != required_description:
  474. if description.lower() == required_description.lower():
  475. logger.warning(f"The description for the measurement with name {name} "
  476. f"was not in the correct case; you provided {description} but "
  477. f"it should be {required_description}. "
  478. "This was automatically corrected.")
  479. measurement['description'] = required_description
  480. else:
  481. raise ValueError(f"The measurement's description {description} "
  482. f"did not match the expected description for this type "
  483. f" ({required_description}). Please correct this, or use "
  484. "'customUnit' as the name.")
  485. if unit not in _ACCEPTABLE_UNITS[name]:
  486. raise ValueError(f"The unit {unit} is not acceptable for measurement {name}. Allowed "
  487. f"units are {_ACCEPTABLE_UNITS[name]}.")
  488. else:
  489. if name != 'customUnit':
  490. logger.warning(f"You provided a measurement with an unknown name {name}. "
  491. "This was corrected to 'customUnit'. Please correct this in your "
  492. "report definition.")
  493. measurement['report_description']['name'] = 'customUnit'
  494. if 'power' in name:
  495. if 'power_attributes' in measurement:
  496. power_attributes = measurement['power_attributes']
  497. if 'voltage' not in power_attributes \
  498. or 'ac' not in power_attributes \
  499. or 'hertz' not in power_attributes:
  500. raise ValueError("The power_attributes of the measurement must contain the "
  501. "following keys: 'voltage' (int), 'ac' (bool), 'hertz' (int).")
  502. else:
  503. raise ValueError("A 'power' related measurement must contain a "
  504. "'power_attributes' section that contains the following "
  505. "keys: 'voltage' (int), 'ac' (boolean), 'hertz' (int)")
  506. def get_active_period_from_intervals(intervals, as_dict=True):
  507. if is_dataclass(intervals[0]):
  508. intervals = [asdict(i) for i in intervals]
  509. period_start = min([i['dtstart'] for i in intervals])
  510. period_duration = max([i['dtstart'] + i['duration'] - period_start for i in intervals])
  511. if as_dict:
  512. return {'dtstart': period_start,
  513. 'duration': period_duration}
  514. else:
  515. from openleadr.objects import ActivePeriod
  516. return ActivePeriod(dtstart=period_start, duration=period_duration)
  517. def determine_event_status(active_period):
  518. if is_dataclass(active_period):
  519. active_period = asdict(active_period)
  520. now = datetime.now(timezone.utc)
  521. if active_period['dtstart'].tzinfo is None:
  522. active_period['dtstart'] = active_period['dtstart'].astimezone(timezone.utc)
  523. active_period_start = active_period['dtstart']
  524. active_period_end = active_period['dtstart'] + active_period['duration']
  525. if now >= active_period_end:
  526. return 'completed'
  527. if now >= active_period_start:
  528. return 'active'
  529. if active_period.get('ramp_up_duration') is not None:
  530. ramp_up_start = active_period_start - active_period['ramp_up_duration']
  531. if now >= ramp_up_start:
  532. return 'near'
  533. return 'far'
  534. async def delayed_call(func, delay):
  535. if isinstance(delay, timedelta):
  536. delay = delay.total_seconds()
  537. await asyncio.sleep(delay)
  538. if asyncio.iscoroutinefunction(func):
  539. await func()
  540. elif asyncio.iscoroutine(func):
  541. await func
  542. else:
  543. func()
  544. def hasmember(obj, member):
  545. """
  546. Check if a dict or dataclass has the given member
  547. """
  548. if is_dataclass(obj):
  549. if hasattr(obj, member):
  550. return True
  551. else:
  552. if member in obj:
  553. return True
  554. return False
  555. def getmember(obj, member):
  556. """
  557. Get a member from a dict or dataclass
  558. """
  559. if is_dataclass(obj):
  560. return getattr(obj, member)
  561. else:
  562. return obj[member]
  563. def setmember(obj, member, value):
  564. """
  565. Set a member of a dict of dataclass
  566. """
  567. if is_dataclass(obj):
  568. setattr(obj, member, value)
  569. else:
  570. obj[member] = value