1
0

imports.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Import operations."""
  2. from __future__ import annotations
  3. from collections import defaultdict
  4. from typing import Dict, List, Optional
  5. from reflex.base import Base
  6. def merge_imports(*imports) -> ImportDict:
  7. """Merge multiple import dicts together.
  8. Args:
  9. *imports: The list of import dicts to merge.
  10. Returns:
  11. The merged import dicts.
  12. """
  13. all_imports = defaultdict(list)
  14. for import_dict in imports:
  15. for lib, fields in import_dict.items():
  16. all_imports[lib].extend(fields)
  17. return all_imports
  18. def collapse_imports(imports: ImportDict) -> ImportDict:
  19. """Remove all duplicate ImportVar within an ImportDict.
  20. Args:
  21. imports: The import dict to collapse.
  22. Returns:
  23. The collapsed import dict.
  24. """
  25. return {lib: list(set(import_vars)) for lib, import_vars in imports.items()}
  26. class ImportVar(Base):
  27. """An import var."""
  28. # The name of the import tag.
  29. tag: Optional[str]
  30. # whether the import is default or named.
  31. is_default: Optional[bool] = False
  32. # The tag alias.
  33. alias: Optional[str] = None
  34. # Whether this import need to install the associated lib
  35. install: Optional[bool] = True
  36. # whether this import should be rendered or not
  37. render: Optional[bool] = True
  38. @property
  39. def name(self) -> str:
  40. """The name of the import.
  41. Returns:
  42. The name(tag name with alias) of tag.
  43. """
  44. if self.alias:
  45. return self.alias if self.is_default else " as ".join([self.tag, self.alias]) # type: ignore
  46. else:
  47. return self.tag or ""
  48. def __hash__(self) -> int:
  49. """Define a hash function for the import var.
  50. Returns:
  51. The hash of the var.
  52. """
  53. return hash((self.tag, self.is_default, self.alias, self.install, self.render))
  54. ImportDict = Dict[str, List[ImportVar]]