PK`NhH99roam.py""" Easily traverse nested Python data structures """ __version__ = "0.3" class _RoamMissingItem: """ Falsey class used to flag item "missing" from traversal path """ def __bool__(self): return False def __len__(self): return 0 def __iter__(self): return self def __next__(self): raise StopIteration() def __repr__(self): return "" MISSING = _RoamMissingItem() class _Path: _r_root_item_ = None _r_steps_ = [] def __init__(self, initial_item, path_to_clone=None): if path_to_clone is not None: self._r_root_item_ = path_to_clone._r_root_item_ self._r_steps_ = list(path_to_clone._r_steps_) # Shallow copy list else: self._r_root_item_ = initial_item self._r_steps_ = [] def log_getattr(self, attr_name: str, roamer: "Roamer"): """ Log the fact that a ``.dot`` attribute lookup was performed using a given name and the given ``Roamer`` shim was produced. """ self._r_steps_.append((f".{attr_name}", unwrap(roamer))) def log_getitem(self, slice_value: slice, roamer: "Roamer"): """ Log the fact that a ``["slice"]`` attribute lookup was performed using a given slice value and the given ``Roamer`` shim was produced. """ if isinstance(slice_value, slice): item_desc = ( f"[{slice_value.start or ''}:{slice_value.stop or ''}" f"{slice_value.step and ':' + slice_value.step or ''}]" ) else: item_desc = f"[{slice_value!r}]" self._r_steps_.append((item_desc, unwrap(roamer))) def _last_found(self): last_found_step = None, None, self._r_root_item_ for i, step in enumerate(self._r_steps_, 1): desc, data = step if data is not MISSING: last_found_step = i, desc, data return last_found_step def _first_missing(self): for i, step in enumerate(self._r_steps_, 1): desc, data = step if data is MISSING: return i, desc, data return None, None, self._r_root_item_ def description(self) -> str: """ Return a text description of this path, capturing: - the first step at which the path was invalid (if applicable) - the type of the root data object - path steps applied - hints about the type and content of data at the point the path became invalid (if applicable) """ result = [] first_missing_index, first_missing_desc, _ = self._first_missing() if first_missing_index: result.append( f"missing step {first_missing_index} {first_missing_desc} for path " ) result.append(f"<{type(self._r_root_item_).__name__}>") result += [desc for desc, _ in self._r_steps_] if first_missing_index: _, _, last_found_data = self._last_found() if last_found_data is not MISSING: result.append(f" at <{type(last_found_data).__name__}>") # Generate hints if isinstance(last_found_data, (tuple, list, set, range)): # Detect an integer key slice operation like `[3]` or `[-2]` if first_missing_desc[0] == "[" and first_missing_desc[-1] == "]": try: int(first_missing_desc[1:-1]) result.append(f" with length {len(last_found_data)}") except ValueError: pass elif isinstance( last_found_data, (str, int, float, complex, bool, bytes, bytearray) ): pass # No hint for primitive types elif last_found_data: try: keys = last_found_data.keys() if keys: result.append( f" with keys [{', '.join([repr(k) for k in keys])}]" ) except AttributeError: attrs = dir(last_found_data) if attrs and not isinstance( last_found_data, (str, tuple, list) ): result.append( f" with attrs [{', '.join([a for a in attrs if not a.startswith('_')])}]" ) return "".join(result) def __eq__(self, other): if isinstance(other, _Path): return ( self._r_root_item_ == other._r_root_item_ and self._r_steps_ == other._r_steps_ ) return False class RoamPathException(Exception): """ An exception raised when a ``Roamer`` shim encounters an invalid path step if that shim has the ``_raise`` option set, or provided when returning data. The ``str()`` representation of this exception is a rich description of where your traversal path went wrong. """ def __init__(self, path): super().__init__(self) self.path = path def __str__(self): return f"" class Roamer: """ Act as a shim over your data objects, to intercept Python operations and do the extra work required to more easily traverse nested data. """ # Internal state variables _r_item_ = None _r_path_ = None _r_is_multi_item_ = False # Options _r_raise_ = False # Temporary flags _r_via_alternate_lookup_ = False _r_item__iter = None def __init__(self, item, _raise=None): # Handle `item` that is itself a `Roamer` if isinstance(item, Roamer): for attr in ("_r_item_", "_r_is_multi_item_", "_r_raise_"): setattr(self, attr, getattr(item, attr)) self._r_path_ = _Path(item._r_item_, item._r_path_) else: self._r_item_ = item self._r_path_ = _Path(self._r_item_) # Set or override raise flag if user provided a value if _raise is not None: self._r_raise_ = bool(_raise) def __getattr__(self, attr_name): # Stop here if no item to traverse if self._r_item_ is MISSING: if not self._r_via_alternate_lookup_: self._r_path_.log_getattr(attr_name, self) return self copy = Roamer(self) # Multi-item: `.xyz` => `(i.xyz for i in item)` if self._r_is_multi_item_: multi_items = [] for i in self._r_item_: lookup = None try: lookup = getattr(i, attr_name) except (TypeError, AttributeError): try: lookup = i[attr_name] except (TypeError, LookupError): pass if isinstance(lookup, (tuple, list, range)): multi_items += lookup elif lookup is not None: multi_items.append(lookup) copy._r_item_ = tuple(multi_items) # Single item: `.xyz` => `item.xyz` else: try: copy._r_item_ = getattr(copy._r_item_, attr_name) except (TypeError, AttributeError): # Attr lookup failed, no more attr lookup options copy._r_item_ = MISSING # Fall back to `self.__getitem__()` if lookup failed so far and we didn't come from there if copy._r_item_ is MISSING and not self._r_via_alternate_lookup_: try: self._r_via_alternate_lookup_ = True copy = self[attr_name] except RoamPathException: pass finally: copy._r_path_.log_getattr(attr_name, copy) self._r_via_alternate_lookup_ = False elif not self._r_via_alternate_lookup_: copy._r_path_.log_getattr(attr_name, copy) if copy._r_item_ is MISSING and copy._r_raise_: raise RoamPathException(copy._r_path_) return copy def __getitem__(self, key_or_index_or_slice): # Stop here if no item to traverse if self._r_item_ is MISSING: if not self._r_via_alternate_lookup_: self._r_path_.log_getitem(key_or_index_or_slice, self) return self copy = Roamer(self) # Multi-item: `[xyz]` => `(i[xyz] for i in item)` if copy._r_is_multi_item_ and not isinstance(key_or_index_or_slice, slice): # Flatten item if we have selected a specific integer index if isinstance(key_or_index_or_slice, int): try: copy._r_item_ = copy._r_item_[key_or_index_or_slice] except (TypeError, LookupError): copy._r_item_ = MISSING # No longer in a multi-item if we have selected a specific index item copy._r_is_multi_item_ = False # Otherwise apply slice lookup to each of multiple items else: multi_items = [] for i in copy._r_item_: lookup = None try: lookup = i[key_or_index_or_slice] except (TypeError, LookupError): try: lookup = getattr(i, key_or_index_or_slice) except (TypeError, AttributeError): pass if isinstance(lookup, (tuple, list, range)): multi_items += lookup elif lookup is not None: multi_items.append(lookup) copy._r_item_ = tuple(multi_items) # Lookup for non-multi item data, or for slice lookups in all cases else: try: copy._r_item_ = copy._r_item_[key_or_index_or_slice] except (TypeError, LookupError): # Index lookup failed, no more index lookup options copy._r_item_ = MISSING # Flag the fact our item actually has multiple elements if isinstance(key_or_index_or_slice, slice): copy._r_is_multi_item_ = True # Fall back to `self.__getattr__()` if lookup failed so far and we didn't come from there if ( copy._r_item_ is MISSING and not self._r_via_alternate_lookup_ # Cannot do an integer attr lookup and not isinstance(key_or_index_or_slice, int) ): try: self._r_via_alternate_lookup_ = True copy = getattr(self, key_or_index_or_slice) except RoamPathException: pass finally: copy._r_path_.log_getitem(key_or_index_or_slice, copy) self._r_via_alternate_lookup_ = False elif not self._r_via_alternate_lookup_: copy._r_path_.log_getitem(key_or_index_or_slice, copy) if copy._r_item_ is MISSING and copy._r_raise_: raise RoamPathException(copy._r_path_) return copy def __call__(self, *args, _raise=False, _roam=False, _invoke=None, **kwargs): if _raise and self._r_item_ is MISSING: raise RoamPathException(self._r_path_) # If an explicit callable is provided, call `_invoke(item, x, y, z)` if _invoke is not None: call_result = _invoke(self._r_item_, *args, **kwargs) # If item is callable: `.(x, y, z)` => `item(x, y, z)` elif callable(self._r_item_): call_result = self._r_item_(*args, **kwargs) # If item is not callable but we were given parameters, try to apply # them even though we know it won't work, to generate the appropriate # exception to let the user know their action failed elif args or kwargs: call_result = self._r_item_(*args, **kwargs) # If item is not callable: `.()` => return wrapped item unchanged else: call_result = self._r_item_ # Re-wrap return as a `Roamer` if requested if _roam: copy = Roamer(self) copy._r_item_ = call_result return copy return call_result def __iter__(self): try: self._r_item__iter = iter(self._r_item_) except (TypeError, AttributeError): self._r_item__iter = None return self def __next__(self): if self._r_item__iter is None: raise StopIteration() next_value = next(self._r_item__iter) return Roamer(next_value) def __eq__(self, other): if isinstance(other, Roamer): for attr in ("_r_item_", "_r_path_", "_r_is_multi_item_", "_r_raise_"): if getattr(other, attr) != getattr(self, attr): return False return True else: return other == self._r_item_ def __bool__(self): return bool(self._r_item_) def __len__(self): try: return len(self._r_item_) except TypeError: # Here we know we have a non-MISSING item, but it doesn't support length lookups so # must be a single thing... # WARNING: This is black magic, does it make enough sense? return 1 def __repr__(self): return f" {self._r_item_!r}>" def r(item: object, _raise: bool = None) -> Roamer: """ A shorter alias for constructing a ``Roamer`` shim class. """ return Roamer(item, _raise=_raise) def r_strict(item: object) -> Roamer: """ A shorter alias for constructing a ``Roamer`` shim class in "strict" mode, which means that the ``_raise`` flag set so the shim will immediately raise a ``RoamPathException`` when you express an invalid path step. """ return Roamer(item, _raise=True) def unwrap(roamer: Roamer, _raise: bool = None) -> object: """ Return the underlying data in the given ``Roamer`` shim object without the need to call that shim object. This is not the recommended way to get data from **roam** but you might prefer it, or it might help to solve unexpected bugs caused by the semi- magical call behaviour. """ result = roamer._r_item_ if _raise and result is MISSING: raise RoamPathException(roamer._r_path_) return result PKXN¸''roam-0.3.dist-info/LICENSE Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS PK!HPOroam-0.3.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,szd&Y)r$[)T&UrPK!HvuVroam-0.3.dist-info/METADATAE*-z>6.bY2R0GL&%`ɳ[bx-˭̕ifrYFJ\@4TҲmr$'*vф_8_u?zP*6 `+JYVz*|U_򯿎1E*X:>Lƹ Wj 5Du( nLw6`|gxty>QgUΌ\'4PLBww`M`frqγjv@ς0+g"l+z73f@cX1QK{O*0Nb^BCzIds\BG  @(GѽUx+î{WJ/b  lKC'*^\P/uBQ\ = h'}ܔ, `sA*geZ:Q<s Gs1ﯻM`>7aBC'}G|GjKMӫ˫ϠJЗ?`l\PfY1,:!b&WsaTxd"19Aa:<:E]RI{#cIMqGkWYa !k*%5Ga9N/,đ yXK1 |uv"z2Tˀ:ӫ#}@q탆 yB/KKJ!M=ۙV{6nܩښz@hZ),|$;%p+O80 Zɼbٗ=ȀKfE  }jI !TE8n5$,OS'8YcI4p%&k8ld#Gr@ ʔ}S(8@%0X95u1O(%r6RyZNc`8i/lX/yT2&10jFG4yŤ{+b1>xrbs"ne8F c 5yi3p@r#0= B:4z5BZiG~g g2k 889zޟ:+?u! kxd{ 0kS8.ËϐdElh&fmP߽PS1R<$ЎAІ CP gbzbG4S7=7!MTk3J𫷔q+Jd B(4ȴ1iO]dbL)fD&TڃdDM,U-mOI3(-#8cP<dz;؝Sl "=hcɖ1a-&ѳl~;߁Wy oU(2a5hç@EͲivofƍ>6CV#<miwMEbfVU q 3y6$vTĀILSbaTP|Эhi\'YbL2UvtNRDIs3K;fe,WFeÎ:aY>&'%*n@O[Ԏ-ѹ վL'լfC4&̾z7vD ' ]cZیk4,8E:VH ;=e2%hKF*伈,"HXv >/R}ѥZEE2;1aK:"xYXN%h:ؚ%.%$uHϝDTg"J}$t?8'#񻝑6O2k&h\lD­lhS cs>0vY sұMv^#,^OGTZ^S+QƎ=g%lKp3ְ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