Coverage for pygeodesy / lazily.py: 96%

216 statements  

« prev     ^ index     » next       coverage.py v7.14.0, created at 2026-08-20 12:21 -0400

1 

2# -*- coding: utf-8 -*- 

3 

4u'''Lazily import C{pygeodesy} modules and attributes, based on 

5U{lazy_import<https://modutil.ReadTheDocs.io/en/latest/#lazy_import>} 

6from I{Brett Cannon}'s U{modutil<https://PyPI.org/project/modutil>}. 

7 

8C{Lazy import} is I{supported only for }U{Python 3.7+ 

9<https://Snarky.Ca/lazy-importing-in-python-3-7>} and is I{enabled by 

10default} in U{PyGeodesy 18.11.10<https://PyPI.org/project/PyGeodesy>} 

11I{and newer}. 

12 

13To I{enable} C{lazy import}, set C{env} variable C{PYGEODESY_LAZY_IMPORT} 

14to C{1}, C{2}, C{3} or higher prior to C{import pygeodesy}. To I{disable} 

15C{lazy import}, set C{env} variable C{PYGEODESY_LAZY_IMPORT} to C{0} or 

16an empty string. Use C{2} or higher to print a message for each lazily 

17imported module and attribute, similar to C{env} variable C{PYTHONVERBOSE} 

18showing imports. Using C{3} or higher also shows the importing file name 

19and line number. 

20 

21@note: C{Lazy import} applies only to top-level modules of C{pygeodesy}. 

22 The C{lazy import} of a top-level module invariably loads all 

23 sub-modules imported by that top-level module. 

24 

25@note: C{Lazy import} raises a L{LazyAttributeError} or L{LazyImportError} 

26 depending on the cause of the error and such errors can occur late, 

27 after all initial imports. 

28''' 

29 

30from pygeodesy import internals as _internals, interns as _interns, \ 

31 _isfrozen # DON'T _lazy_import2 

32# from pygeodesy.errors import _error_init, _ImmutableError, _xkwds_get, _xkwds_item2 # _ALL_MODS 

33from pygeodesy.internals import _caller3, _envPYGEODESY, _headof, printf, _Property_RO, \ 

34 _tailof, typename, _versions # _getenv, _PYGEODESY_ENV, \ 

35# _MODS_Base, _MODS.sys_version_info2 

36from pygeodesy.interns import _attribute_, _by_, _COLONSPACE_, _COMMASPACE_, _DALL_, \ 

37 _DMAIN_, _doesn_t_exist_, _DOT_, _EQUALSPACED_, _from_, \ 

38 _HASH_, _line_, _module_, NN, _no_, _not_, _pygeodesy_, \ 

39 _pygeodesy_abspath_, _SPACE_, _SUB_PACKAGES, _or_, \ 

40 _UNDER_, _version_, _sys, _intern # function, _1_ 

41try: 

42 from importlib import import_module # in .rdnap._v_grid 

43except ImportError as x: # Python 2.6- 

44 raise ImportError(_COLONSPACE_(x, _versions())) 

45# import sys as _sys # from .interns 

46 

47_a0 = () # PYCHOK empty tuple 

48_asSPACED_ = ' as ' 

49_FOR_DOCS = _envPYGEODESY('FOR_DOCS') # for epydoc ... 

50_imported_ = 'imported' 

51_init__all__ = _FOR_DOCS or _envPYGEODESY('_init__all__', _DALL_) == _DALL_ # PYCHOK exported 

52_lazily_ = 'lazily' 

53_PYTHON_X_DEV = getattr(_sys.flags, 'dev_mode', False) # PYCHOK Python 3.2+ 

54_unlazy = _unLazy0 = _isfrozen or _internals._MODS.sys_version_info2 < (3, 7) # PYCHOK mod.__getattr__ 3.7+ 

55_WARNINGS_X_DEV = _envPYGEODESY('WARNINGS') and (_PYTHON_X_DEV or bool(_sys.warnoptions)) # PYCHOK .props 

56 

57# @module_property[_RO?] <https://GitHub.com/jtushman/proxy_tools/> <https://discuss.Python.org/t/47379> 

58isLazy = None # see @var isLazy in .__init__ 

59 

60 

61class LazyAttributeError(AttributeError): 

62 '''Raised if a C{lazily imported} attribute is missing or invalid. 

63 ''' 

64 def __init__(self, *args, **kwds): 

65 _ALL_MODS.errors._error_init(AttributeError, self, args, **kwds) 

66 

67 

68class LazyImportError(ImportError): 

69 '''Raised if C{lazy import} is not supported, disabled or failed. 

70 ''' 

71 def __init__(self, *args, **kwds): 

72 _ALL_MODS.errors._error_init(ImportError, self, args, **kwds) 

73 

74 

75class _Dict(dict): 

76 '''(INTERNAL) Imports C{dict}. 

77 ''' 

78 _name = NN 

79 

80 def __getattr__(self, attr): 

81 try: 

82 return self[attr] 

83 except KeyError: 

84 return dict.__getattr__(self, attr) 

85 

86# def __setattr__(self, attr, value): 

87# if attr in self: 

88# self[attr] = value 

89# else: 

90# dict.__setattr__(self, attr, value) 

91 

92 def add(self, name, mod_, *subs): 

93 '''Add a C{[name] = mod_} item. 

94 

95 @raise AssertionError: The B{C{name}} already exists 

96 with a different B{C{mod_}}. 

97 ''' 

98 try: 

99 sub = self[name] # duplicate OK 

100 if sub != mod_ and sub not in subs: 

101 t = _DOT_(self._name, name) 

102 t = _COLONSPACE_(t, repr(sub)) 

103 t = _COMMASPACE_(t, _not_(repr(mod_))) 

104 raise AssertionError(t) 

105 except KeyError: 

106 self[name] = mod_ 

107 

108 def _NAME(self, which): 

109 self._name = _intern(typename(which).upper()) 

110 

111 

112class _NamedEnum_RO(dict): 

113 '''(INTERNAL) C{Read_Only} enum-like C{dict} sub-class. 

114 ''' 

115# _name = NN # also first kwd, __init__(_name=...) 

116 

117 def _DOT_(self, attr): # PYCHOK no cover 

118 return _DOT_(self._name, attr) # PYCHOK _name 

119 

120 def __getattr__(self, attr): 

121 try: 

122 return self[attr] 

123 except KeyError: 

124 t = self._DOT_(attr) 

125 raise LazyAttributeError(t, txt=_doesn_t_exist_) 

126 

127 def __setattr__(self, attr, value): # PYCHOK no cover 

128 e = _ALL_MODS.errors 

129 raise e._ImmutableError(self, attr, value, 

130 Error=LazyAttributeError) 

131 

132 def enums(self): 

133 # Yield all C{(mod_, tuple)} pairs 

134 for m, t in dict.items(self): 

135 n = m.replace(_UNDER_, _DOT_) 

136 if n != m: 

137 if m.startswith(_UNDER_): 

138 continue # skip _name= ... 

139 u = m.rstrip(_UNDER_) 

140 if u != m: 

141 u = len(u) 

142 n = n[:u] + m[u:] 

143 yield n, t 

144 

145 def fill_D(self, _D, which): 

146 # Fill C{_Dict _D}. 

147 _D._NAME(which) 

148 _a = _D.add 

149 for m, t in self.enums(): 

150 _a(m, _DOT_(m, NN, NN)) # import module 

151 for a in t: 

152 a, _, as_ = a.partition(_asSPACED_) 

153 if as_: # import attr as attr_ 

154 _a(as_, _DOT_(m, a, NN), *_SUB_PACKAGES) 

155 else: 

156 _a(a, m) 

157 return _D 

158 

159 

160def _a(*names): 

161 '''(INTERNAL) Intern all C{names}. 

162 ''' 

163 return tuple(map(_intern, names)) if names else _a0 

164 

165 

166def _ALL_ATTRS(*attrs): 

167 '''(INTERNAL) Unravel all exported module attributes. 

168 ''' 

169 t = () 

170 for attr in attrs: 

171 t += tuple(map(_getattras, attr)) 

172 return t 

173 

174 

175_ALL_INIT = _a(_pygeodesy_abspath_, _version_) 

176 

177# __all__ value for most modules, accessible as _ALL_LAZY.<module> 

178_ALL_LAZY = _NamedEnum_RO(_name='_ALL_LAZY', 

179 albers=_a('AlbersEqualArea', 'AlbersEqualArea2', 'AlbersEqualArea4', 

180 'AlbersEqualAreaCylindrical', 'AlbersEqualAreaNorth', 'AlbersEqualAreaSouth', 

181 'AlbersError', 'Albers7Tuple'), 

182 angles=_a('Ang', 'Deg', 'Lambertian', 'Rad', 'isAng'), 

183 auxilats=_a(), # package only 

184 azimuthal=_a('AzimuthalError', 'Azimuthal7Tuple', 

185 'Equidistant', 'EquidistantExact', 'EquidistantGeodSolve', 'EquidistantKarney', 

186 'Gnomonic', 'GnomonicExact', 'GnomonicGeodSolve', 'GnomonicKarney', 

187 'LambertEqualArea', 'Orthographic', 'Stereographic', 

188 'equidistant', 'gnomonic'), 

189 basics=_a('clips', 'copysign0', 'copytype', 'halfs2', 

190 'int1s', 'isbool', 'isCartesian', 'isclass', 'iscomplex', 'isDEPRECATED', 'isfloat', 

191 'isidentifier', 'isinstanceof', 'isint', 'isiterable', 'isiterablen', 'isiterabletype', 

192 'iskeyword', 'isLatLon', 'islistuple', 'isNvector', 'isodd', 

193 'isscalar', 'issequence', 'isstr', 'issubclassof', 'itemsorted', 

194 'len2', 'map1', 'map2', 'max2', 'min2', 'neg', 'neg_', 

195 'signBit', 'signOf', 'splice', 'str2ub', 'ub2str', 'unsigned0'), 

196 booleans=_a('BooleanFHP', 'BooleanGH', 'LatLonFHP', 'LatLonGH', 

197 'isBoolean'), 

198 cartesianBase=_a('RadiusThetaPhi3Tuple', 'rtp2xyz', 'rtp2xyz_', 'xyz2rtp', 'xyz2rtp_'), 

199 clipy=_a('ClipCS4Tuple', 'ClipFHP4Tuple', 'ClipGH4Tuple', 'ClipLB6Tuple', 'ClipSH3Tuple', 

200 'clipCS4', 'clipFHP4', 'clipGH4', 'clipLB6', 'clipSH', 'clipSH3'), 

201 css=_a('CassiniSoldner', 'Css', 'CSSError', 'toCss', 

202 'EasNorAziRk4Tuple', 'EasNorAziRkEqu6Tuple', 'LatLonAziRk4Tuple'), 

203 constants=_a('DIG', 'EPS', 'EPS0', 'EPS02', 'EPS1', 'EPS2', 'EPS4', 'EPS8', 'EPS_2', 

204 'INF', 'INT0', 'MANT_DIG', 'MAX', 'MAX_EXP', 'MIN', 'MIN_EXP', 'NAN', 'NEG0', 'NINF', 

205 'OVERFLOW', 'PI', 'PI2', 'PI_2', 'PI3', 'PI_3', 'PI3_2', 'PI4', 'PI_4', 'PI_6', 

206 'R_FM', 'R_GM', 'R_KM', 'R_M', 'R_MA', 'R_MB', 'R_NM', 'R_QM', 'R_SM', 'R_VM', 

207 'float_', 'float0_', 'floats_', 'isclose', 'isfinite', 'isinf', 'isint0', 

208 'isnan', 'isnear0', 'isnear1', 'isnear90', 'isneg', 'isneg0', 'isninf', 'isnon0', 

209 'remainder'), 

210 datums=_a('Datum', 'Datums', 'Similarity', 'Transform', 'Transforms'), 

211# deprecated=_a(), # module only 

212 dms=_a('F_D', 'F_DM', 'F_DMS', 'F_DEG', 'F_MIN', 'F_SEC', 'F_D60', 'F__E', 'F__F', 'F__G', 'F_RAD', 

213 'F_D_', 'F_DM_', 'F_DMS_', 'F_DEG_', 'F_MIN_', 'F_SEC_', 'F_D60_', 'F__E_', 'F__F_', 'F__G_', 'F_RAD_', 

214 'F_D__', 'F_DM__', 'F_DMS__', 'F_DEG__', 'F_MIN__', 'F_SEC__', 'F_D60__', 'F__E__', 'F__F__', 'F__G__', 'F_RAD__', 

215 'S_DEG', 'S_MIN', 'S_SEC', 'S_DMS', 'S_RAD', 'S_SEP', 

216 'bearingDMS', 'clipDegrees', 'clipRadians', 'compassDMS', 'compassPoint', 

217 'degDMS', 'latDMS', 'latlonDMS', 'latlonDMS_', 'lonDMS', 'normDMS', 

218 'parseDDDMMSS', 'parseDMS', 'parseDMS2', 'parse3llh', 'parseRad', 'precision', 'toDMS'), 

219 ecef=_a('EcefFarrell21', 'EcefFarrell22', 'EcefKarney', 'EcefSudano', 'EcefUPC', 'EcefVeness', 'EcefYou', 

220 'EcefError', 'EcefMatrix', 'Ecef9Tuple'), 

221 ecefLocals=_a(), # module only 

222 elevations=_a('Elevation2Tuple', 'GeoidHeight2Tuple', 

223 'elevation2', 'geoidHeight2'), 

224 ellipses=_a('Ellipse', 'EllipseError'), 

225 ellipsoidalBase=_a(), # module only 

226 ellipsoidalBaseDI=_a(), # module only 

227 ellipsoidalExact=_a(), # module only 

228 ellipsoidalGeodSolve=_a(), # module only 

229 ellipsoidalKarney=_a(), # module only 

230 ellipsoidalNvector=_a(), # module only 

231 ellipsoidalVincenty=_a('VincentyError',), # nothing else 

232 ellipsoids=_a('a_f2Tuple', 'Curvature2Tuple', 

233 'Ellipsoid', 'Ellipsoid2', 'Ellipsoids', 

234 'a_b2e', 'a_b2e2', 'a_b2e22', 'a_b2e32', 'a_b2f', 'a_b2f_', 'a_b2f2', 'a_b2n', 

235 'a_f2b', 'a_f_2b', 'b_f2a', 'b_f_2a', 

236 'e2f', 'e22f', 

237 'f2e2', 'f2e22', 'f2e32', 'f_2f', 'f2f_', 'f2f2', 'f2n', 'n2e2', 'n2f', 'n2f_'), 

238 elliptic=_a('Elliptic', 'EllipticError', 'Elliptic3Tuple'), 

239 epsg=_a('Epsg', 'EPSGError'), 

240 errors=_a('AuxError', 'ClipError', 'CrossError', 'GeodesicError', 'IntersectionError', 

241 'NumPyError', 'LenError', 'LimitError', 'MGRSError', 

242 'ParseError', 'PointsError', 'RangeError', 'RhumbError', 

243 'SciPyError', 'SciPyWarning', 'TRFError', 'TriangleError', 'UnitError', 'VectorError', 

244 'crosserrors', 'exception_chaining', 'isError', 'limiterrors', 'rangerrors'), 

245 etm=_a('Etm', 'ETMError', 'ExactTransverseMercator', 

246 'parseETM5', 'toEtm8'), 

247 fmath=_a('Fdot', 'Fdot_', 'Fhorner', 'Fhypot', 'Fpolynomial', 'Fpowers', 'Fcbrt', 'Froot', 'Fsqrt', 

248 'bqrt', 'cbrt', 'cbrt2', 'euclid', 'euclid_', 

249 'facos1', 'fasin1', 'fatan', 'fatan1', 'fatan2', 'favg', 

250 'fdot', 'fdot_', 'fdot3', 'fma', 'fmean', 'fmean_', 'fhorner', 'fidw', 'f2mul_', 

251 'fpolynomial', 'fpowers', 'fprod', 'frandoms', 'frange', 'freduce', 'fremainder', 

252 'hypot', 'hypot_', 'hypot1', 'hypot2', 'hypot2_', 

253 'norm2', 'norm_', 'polar2', 'polar2d', 

254 'sqrt0', 'sqrt3', 'sqrt_a', 'zcrt', 'zqrt'), 

255 formy=_a('Radical2Tuple', 

256 'angle2chord', 'antipode', 'antipode_', 'bearing', 'bearing_', 

257 'chord2angle', 'compassAngle', 'cosineLaw', 'cosineLaw_', 

258 'equirectangular', 'equirectangular4', 'euclidean', 'euclidean_', 

259 'excessAbc_', 'excessCagnoli_', 'excessGirard_', 'excessLHuilier_', 

260 'excessKarney', 'excessKarney_', 'excessQuad', 'excessQuad_', 

261 'flatLocal', 'flatLocal_', 'flatPolar', 'flatPolar_', 

262 'hartzell', 'haversine', 'haversine_', 'heightOf', 'heightOrthometric', 'horizon', 'hubeny', 'hubeny_', 

263 'intersection2', 'intersections2', 'isantipode', 'isantipode_', 'isnormal', 'isnormal_', 

264 'normal', 'normal_', 'opposing', 'opposing_', 'radical2', 

265 'thomas', 'thomas_', 'vincentys', 'vincentys_'), 

266 frechet=_a('Frechet', 'FrechetDegrees', 'FrechetError', 'FrechetRadians', 'FrechetCosineLaw', 

267 'FrechetDistanceTo', 'FrechetEquirectangular', 'FrechetEuclidean', 'FrechetExact', 

268 'FrechetFlatLocal', 'FrechetFlatPolar', 'FrechetHaversine', 'FrechetHubeny', 'FrechetKarney', 

269 'FrechetThomas', 'FrechetVincentys', 'Frechet6Tuple', 

270 'frechet_'), 

271 fstats=_a('Fcook', 'Flinear', 'Fwelford'), 

272 fsums=_a('Fsum', 'DivMod2Tuple', 'Fsum2Tuple', 'ResidualError', 

273 'f2product', 'fsum', 'fsum_', 'fsumf_', 'fsum1', 'fsum1_', 'fsum1f_', 'nonfiniterrors'), 

274 gars=_a('Garef', 'GARSError'), 

275 geodesici=_a('Intersectool', 'Intersectool5Tuple', 'Intersect7Tuple', 

276 'Intersector', 'Intersector5Tuple', 'Middle5Tuple', 'XDict'), 

277 geodesicw=_a('Geodesic', 'GeodesicLine', 'Geodesic_WGS84'), 

278 geodesicx=_a('gx', 'gxarea', 'gxbases', 'gxline', # modules 

279 'GeodesicAreaExact', 'GeodesicExact', 'GeodesicLineExact', 'PolygonArea'), 

280 geodsolve=_a('GeodesicSolve', 'GeodesicLineSolve', 'GeodSolve12Tuple'), 

281 geod3solve=_a('Geodesic3Solve', 'GeodesicLine3Solve', 'Geod3Solve8Tuple', 'Geodesic3Error'), 

282 geohash=_a('Geohash', 'Geohashed', 'GeohashError', 'Neighbors8Dict', 'Resolutions2Tuple', 'Sizes3Tuple'), 

283 geoids=_a('GeoidError', 'GeoidEGM96', 'GeoidG2012B', 'GeoidKarney', 'GeoidPGM', 'egmGeoidHeights', 

284 'PGMError', 'GeoidHeight5Tuple'), 

285 hausdorff=_a('Hausdorff', 'HausdorffDegrees', 'HausdorffError', 'HausdorffRadians', 'HausdorffCosineLaw', 

286 'HausdorffDistanceTo', 'HausdorffEquirectangular', 'HausdorffEuclidean', 'HausdorffExact', 

287 'HausdorffFlatLocal', 'HausdorffFlatPolar', 'HausdorffHaversine', 'HausdorffHubeny', 

288 'HausdorffKarney', 'HausdorffThomas', 'HausdorffVincentys', 'Hausdorff6Tuple', 

289 'hausdorff_', 'randomrangenerator'), 

290 heights=_a('HeightCubic', 'HeightError', 'HeightIDWcosineLaw', 'HeightIDWdistanceTo', 

291 'HeightIDWequirectangular', 'HeightIDWeuclidean', 'HeightIDWexact', 'HeightIDWflatLocal', 

292 'HeightIDWflatPolar', 'HeightIDWhaversine', 'HeightIDWhubeny', 'HeightIDWkarney', 'HeightIDWthomas', 

293 'HeightIDWvincentys', 'HeightLinear', 'HeightLSQBiSpline', 'HeightSmoothBiSpline'), 

294 internals=_internals.__all__, 

295 interns=_interns.__all__, 

296 iters=_a('LatLon2PsxyIter', 'PointsIter', 'points2', 

297 'isNumpy2', 'isPoints2', 'isTuple2', 'iterNumpy2', 'iterNumpy2over'), 

298 karney=_a('Area3Tuple', 'Caps', 'Direct9Tuple', 'GDict', 'Inverse10Tuple'), 

299 ktm=_a('KTMError', 'KTransverseMercator'), 

300 latlonBase=_a('latlon2n_xyz', 'philam2n_xyz'), 

301 lazily=_a('LazyAttributeError', 'LazyImportError', 'isLazy'), 

302 lcc=_a('Conic', 'Conics', 'Lcc', 'LCCError', 'toLcc'), 

303 ltp=_a('Attitude', 'AttitudeError', 'Frustum', 

304 'LocalCartesian', 'LocalError', 'Ltp', 'LqRD', 'tyr3d'), 

305 ltpTuples=_a('Aer', 'Aer4Tuple', 'Attitude4Tuple', 

306 'Enu', 'Enu4Tuple', 'Footprint5Tuple', 'Local9Tuple', 'Los', 

307 'Ned', 'Ned4Tuple', 'Uvw', 'Uvw3Tuple', 'XyzLocal', 'Xyz4Tuple'), 

308 mgrs=_a('Mgrs', 'parseMGRS', 'toMgrs', 'Mgrs4Tuple', 'Mgrs6Tuple'), 

309 named=_a('ADict', 

310 'callername', 'classname', 'classnaming', 'modulename', 

311 'nameof', 'notImplemented', 'notOverloaded'), 

312 namedTuples=_a('Bearing2Tuple', 'Bounds2Tuple', 'Bounds4Tuple', 

313 'Circle4Tuple', 'Destination2Tuple', 'Destination3Tuple', 

314 'Distance2Tuple', 'Distance3Tuple', 'Distance4Tuple', 

315 'EasNor2Tuple', 'EasNor3Tuple', 'Ellipse5Tuple', 

316 'Forward4Tuple', 'Intersection3Tuple', 

317 'LatLon2Tuple', 'LatLon3Tuple', 'LatLon4Tuple', 

318 'LatLonDatum3Tuple', 'LatLonDatum5Tuple', 'LatLonHeight3Tuple', 'LatLonNgeoid3Tuple', 

319 'LatLonPrec3Tuple', 'LatLonPrec5Tuple', 

320 'NearestOn2Tuple', 'NearestOn3Tuple', 'NearestOn6Tuple', 'NearestOn8Tuple', 

321 'PhiLam2Tuple', 'PhiLam3Tuple', 'PhiLam4Tuple', 'PhiLamHeight3Tuple', 'PhiLamNgeoid3Tuple', 

322 'Point3Tuple', 'Points2Tuple', 

323 'RD4Tuple', 'Reverse4Tuple', 'Triangle7Tuple', 'Triangle8Tuple', 'Trilaterate5Tuple', 

324 'UtmUps2Tuple', 'UtmUps5Tuple', 'UtmUps8Tuple', 'UtmUpsLatLon5Tuple', 

325 'Vector2Tuple', 'Vector3Tuple', 'Vector4Tuple'), 

326 nvectorBase=_a('NorthPole', 'SouthPole', 'n_xyz2latlon', 'n_xyz2philam'), 

327 osgr=_a('Osgr', 'OSGRError', 'parseOSGR', 'toOsgr'), 

328 points=_a('LatLon_', 'LatLon2psxy', 'Numpy2LatLon', 'Shape2Tuple', 'Tuple2LatLon', 

329 'areaOf', 'boundsOf', 'centroidOf', 'fractional', 

330 'isclockwise', 'isconvex', 'isconvex_', 'isenclosedBy', 'ispolar', 

331 'luneOf', 'nearestOn5', 'perimeterOf', 'quadOf'), 

332 props=_a('Property', 'Property_RO', 'property_doc_', 

333 'property_RO', 'property_ROnce', 'property_ROver', 

334 'deprecated_class', 'deprecated_function', 'deprecated_method', 

335 'deprecated_Property_RO', 'deprecated_property_RO', 'DeprecationWarnings'), 

336 resections=_a('Collins5Tuple', 'ResectionError', 'Survey3Tuple', 'Tienstra7Tuple', 

337 'TriAngle5Tuple', 'TriSide2Tuple', 'TriSide4Tuple', 

338 'cassini', 'collins5', 'pierlot', 'pierlotx', 'tienstra7', 

339 'snellius3', 'wildberger3', 

340 'triAngle', 'triAngle5', 'triArea', 'triSide', 'triSide2', 'triSide4'), 

341 rhumb=_a(), # package only 

342 rhumb_aux_=_a('RhumbAux', 'RhumbLineAux'), 

343 rhumb_ekx=_a('Rhumb', 'RhumbLine'), 

344 rhumb_solve=_a('RhumbSolve', 'RhumbLineSolve', 'RhumbSolve7Tuple', 'Rhumb8Tuple'), # in .karney 

345 sphericalBase=_a(), # module only 

346 sphericalNvector=_a(), # module only 

347 sphericalTrigonometry=_a(), # module only 

348 simplify=_a('simplify1', 'simplifyRDP', 'simplifyRW', 'simplifyVW'), 

349 solveBase=_a(), # module only 

350 streprs=_a('anstr', 'attrs', 'enstr2', 'fstr', 'fstrzs', 'hstr', 'instr', 

351 'lrstrip', 'pairs', 'reprs', 'strs', 'unstr'), 

352 trf=_a('RefFrame', 'RefFrames', 'TransformXform', 'TRFXform', 'TRFXform7Tuple', 

353 'date2epoch', 'epoch2date', 'trfTransform0', 'trfTransforms', 'trfXform'), 

354 triaxials=_a(), # package only 

355 triaxials_bases=_a('LLK', 'TriaxialError'), 

356 triaxials_conformal3=_a('BetOmgGam5Tuple', 

357 'Conformal3', 'Conformal3B', 'Conformal3Sphere', 'Conformal5Tuple'), 

358 triaxials_triaxial3=_a('BetOmgAlp5Tuple', 'Cartesian5Tuple', 'LatLonAzi5Tuple', 'PhiLamZet5Tuple', 

359 'Triaxial3', 'Triaxial3B', 'Triaxial3s'), 

360 triaxials_triaxial5=_a('BetaOmega2Tuple', 'BetaOmega3Tuple', 

361 'Conformal', 'ConformalSphere', 'Conformal2Tuple', 

362 'Triaxial', 'Triaxial_', 'Triaxials', 'hartzell4', 'height4'), 

363 units=_a('Azimuth', 'Band', 'Bearing', 'Bearing_', 'Bool', 

364 'Degrees', 'Degrees_', 'Degrees2', 'Distance', 'Distance_', 'Easting', 'Epoch', 

365 'Feet', 'FIx', 'Float_', 'Height', 'Height_', 'HeightX', 'Int_', 

366 'Lam', 'Lamd', 'Lat', 'Lat_', 'Lon', 'Lon_', 

367 'Meter', 'Meter_', 'Meter2', 'Meter3', 'Northing', 'Number_', 

368 'Phi', 'Phid', 'Precision_', 'Radians', 'Radians_', 'Radians2', 

369 'Radius_', 'Scalar', 'Scalar_', 'Zone'), 

370 unitsBase=_a('Float', 'Int', 'Radius', 'Str'), 

371 ups=_a('Ups', 'UPSError', 'parseUPS5', 'toUps8', 'upsZoneBand5'), 

372 utily=_a('acos1', 'acre2ha', 'acre2m2', 'agdf', 'asin1', 

373 'atan1', 'atan1d', 'atan2', 'atan2b', 'atan2d', 'atan2p', 

374 'chain2m', 'circle4', 'cot', 'cot_', 'cotd', 'cotd_', 

375 'degrees', 'degrees90', 'degrees180', 'degrees360', 'degrees2grades', 'degrees2m', 

376 'fathom2m', 'ft2m', 'furlong2m', # 'degrees2grades as degrees2gons', 

377 'gdf', 'grades', 'grades400', 'grades2degrees', 'grades2radians', 

378# 'grades as gons', 'grades400 as gons400', 'grades2degrees as gons2degrees', 'grades2radians as gons2radians', 

379 'ha2acre', 'ha2m2', 'hav', 'km2m', 

380 'm2acre', 'm2chain', 'm2degrees', 'm2fathom', 'm2ft', 'm2furlong', 

381 'm2ha', 'm2km', 'm2NM', 'm2radians', 'm2SM', 'm2toise', 'm2yard', 

382 'NM2m', 'radians', 'radiansPI', 'radiansPI2', 'radiansPI_2', 'radians2m', 

383 'sincos2', 'SinCos2', 'sincos2_', 'sincos2d', 'sincos2d_', 'sincostan3', 'sincostan3d', 'SM2m', 

384 'tan', 'tan_', 'tand', 'tand_', 'tan_2', 'tanPI_2_2', 'toise2m', 'truncate', 

385 'unroll180', 'unrollPI', 

386 'wrap90', 'wrap180', 'wrap360', 'wrapPI_2', 'wrapPI', 'wrapPI2', 'wrap_normal', 

387 'yard2m'), 

388 utm=_a('Utm', 'UTMError', 'parseUTM5', 'toUtm8', 'utmZoneBand5'), 

389 utmups=_a('UtmUps', 'UTMUPSError', 'parseUTMUPS5', 'toUtmUps8', 

390 'utmupsValidate', 'utmupsValidateOK', 'utmupsZoneBand5'), 

391 utmupsBase=_a(), # module only 

392 vector2d=_a('Circin6Tuple', 'Circum3Tuple', 'Circum4Tuple', 'Meeus2Tuple', 'Radii11Tuple', 'Soddy4Tuple', 'Triaxum5Tuple', 

393 'circin6', 'circum3', 'circum4', 'circum4_', 'meeus2', 'radii11', 'soddy4', 'triaxum5', 'trilaterate2d2'), 

394 vector3d=_a('Vector3d', 'intersection3d3', 'iscolinearWith', 'nearestOn', 'nearestOn6', 'parse3d', 

395 'trilaterate3d2'), 

396 vector3dBase=_a(), # module only 

397 webmercator=_a('Wm', 'WebMercatorError', 'parseWM', 'toWm', 'EasNorRadius3Tuple'), 

398 wgrs=_a('Georef', 'WGRSError'),) 

399 

400_ALL_DEPRECATED = _NamedEnum_RO(_name='_ALL_DEPRECATED', 

401 deprecated=_a('bases', 'datum', 'nvector', # DEPRECATED modules and ... 

402 'rhumbaux', 'rhumbBase', 'rhumbsolve', 'rhumbx'), # ... names 

403 deprecated_bases=_a('LatLonHeightBase', 'points2'), 

404 deprecated_classes=_a('ChLV', 'ChLVa', 'ChLVe', 'ChLVEN2Tuple', 'ChLV9Tuple', 'ChLVYX2Tuple', 'ChLVyx2Tuple', 

405 'ClipCS3Tuple', 'EasNorExact4Tuple', 'EcefCartesian', 'Fn_rt', 

406 'FrechetCosineAndoyerLambert', 'FrechetCosineForsytheAndoyerLambert', 

407 'HausdorffCosineAndoyerLambert', 'HausdorffCosineForsytheAndoyerLambert', 

408 'HeightIDW', 'HeightIDW2', 'HeightIDW3', 'HeightIDWcosineAndoyerLambert', 

409 'HeightIDWcosineForsytheAndoyerLambert', 'Helmert7Tuple', 

410 'JacobiConformal', 'JacobiConformalSpherical', 'Jacobi2Tuple', 

411 'Lam_', 'LatLonExact4Tuple', 'NearestOn4Tuple', 'Ned3Tuple', 

412 'Phi_', 'RefFrameError', 'Rhumb7Tuple', 'RhumbOrder2Tuple', 

413 'Transform7Tuple', 'TriAngle4Tuple', 'UtmUps4Tuple', 'XDist'), 

414 deprecated_consterns=_a('Elliperim', 'EPS1_2', 'MANTIS', 'OK'), 

415 deprecated_datum=_a('Curvature2Tuple', 'Datum', 'Ellipsoid', 'Transform', # assert 

416 'Datums', 'Ellipsoids', 'Transforms', 

417 'R_FM', 'R_KM', 'R_M', 'R_MA', 'R_MB', 'R_NM', 'R_SM', 'R_VM'), 

418 deprecated_functions=_a('anStr', 'areaof', 'atand', 'bounds', # most of the DEPRECATED functions, except ellipsoidal ... 

419 'clipCS3', 'clipDMS', 'clipStr', 'collins', 'copysign', # ... and spherical flavors 

420 'cosineAndoyerLambert', 'cosineAndoyerLambert_', 

421 'cosineForsytheAndoyerLambert', 'cosineForsytheAndoyerLambert_', 

422 'decodeEPSG2', 

423 'elliperim', 'elliperim_', 'encodeEPSG', 'enStr2', 'equirectangular_', 'equirectangular3', 

424 'excessAbc', 'excessGirard', 'excessLHuilier', 

425 'false2f', 'falsed2f', 'float0', 'fStr', 'fStrzs', 'Fsum2product', 

426 'hypot3', 'inStr', 'isenclosedby', 'istuplist', 

427 'joined', 'joined_', 'nearestOn3', 'nearestOn4', 

428 'parseUTM', 'perimeterof', 'polygon', 

429 'scalar', 'simplify2', 'simplifyRDPm', 'simplifyVWm', 

430 'tienstra', 'toUtm', 'triAngle4', 

431 'unsign0', 'unStr', 'utmZoneBand2'), 

432 deprecated_nvector=_a('LatLonNvectorBase', 'Nvector', 'sumOf', 'NorthPole', 'SouthPole'),) 

433 

434 

435class _ALL_MODS(_internals._MODS_Base): 

436 '''(INTERNAL) Memoized import of any L{pygeodesy} module. 

437 ''' 

438 def __getattr__(self, name): 

439 '''Get a C{pygeodesy} module or attribute by B{C{name}}. 

440 

441 @arg name: Un/qualified module or qualified attribute name (C{str}). 

442 

443 @raise ImportError: Importing module B{C{name}} failed. 

444 

445 @raise AttributeError: No attribute named B{C{name}}. 

446 ''' 

447 try: 

448 v = _lazy_dict[name] # package.__dict__ 

449 except KeyError: 

450 v = _lazy_module(name) # package.__getattr__ 

451 if _tailof(typename(v)) != name: 

452 try: 

453 v = getattr(v, _tailof(name)) 

454 except AttributeError: 

455 pass # XXX LazyAttributeError? 

456 return v 

457 

458 def getattr(self, name, *attr_dflt): # , parent=_pygeodesy_ 

459 '''Get an attribute of/or a C{pygeodesy} module. 

460 

461 @arg name: Un/qualified module name (C{str}). 

462 @arg attr_dflt: Optional attribute name (C{str}) and 

463 optional default value (any C{type}). 

464 

465 @return: The C{pygeodesy} module's attribute value. 

466 

467 @raise ImportError: Importing module B{C{name}} failed. 

468 

469 @raise AttributeError: No attribute named B{C{attr}}. 

470 ''' 

471 v = self.getmodule(name) 

472 if attr_dflt: 

473 v = getattr(v, *attr_dflt) 

474 return v 

475 

476 def getmodule(self, name, parent=_pygeodesy_): 

477 '''Get a C{pygeodesy} module or the C{__main__}. 

478 

479 @arg name: Un/qualified module name (C{str}). 

480 

481 @return: The C{pygeodesy} module. 

482 

483 @raise ImportError: Importing module B{C{name}} failed. 

484 ''' 

485 if _headof(name) != parent and name != _DMAIN_: 

486 name = _DOT_(parent, name) 

487 try: 

488 return _sys.modules[name] 

489 except KeyError: 

490 return _getmodule(name, parent) 

491 

492 def imported(self, name): 

493 '''Return module or package C{name} if already imported. 

494 ''' 

495 return _sys.modules.get(name, None) 

496 

497 def into(self, **mod_DNAME): 

498 '''Deferred import of module C{mod} into module C{_DNAME_} 

499 and overwrite C{_DNAME_._mod} to module C{mod}, I{once} 

500 at the first access of an attribute of module C{mod}. 

501 ''' 

502 # assert len(mod_DNAME) == 1 

503 # mod, dun = mod_DNAME.popitem() 

504 

505 class _Into(object): 

506 

507 def __getattr__(unused, name): 

508 m = _getmodinto(mod_DNAME, _Into) 

509 return getattr(m, name) 

510 

511 return _Into() 

512 

513# @_Property_RO 

514# def _isBoolean(self): 

515# '''(INTERNAL) Get function C(.booleans.isBoolean}, I{once}. 

516# ''' 

517# return self.booleans.isBoolean 

518 

519 def items(self): # no module named 'items' 

520 '''Yield the modules imported so far. 

521 ''' 

522 for n, m in _sys.modules.items(): 

523 if _headof(n) == _pygeodesy_: 

524 yield n, m 

525 

526 @_Property_RO 

527 def _triaxials_triaxial5(self): 

528 '''(INTERNAL) Get module C{triaxial.triaxials}. 

529 ''' 

530 return self.triaxials.triaxial5 

531 

532_internals._MODS = _ALL_MODS = _ALL_MODS() # PYCHOK singleton 

533 

534 

535def _ALL_OTHER(*objs): 

536 '''(INTERNAL) Get class and function B{C{objs}} for __all__. 

537 ''' 

538 def _interned(o): # intern'd base name 

539 n = _tailof(typename(o)) 

540 i = NN(_UNDER_, n, _UNDER_) # intern'd 

541 return getattr(_interns, i, n) 

542 

543 return tuple(map(_interned, objs)) # map2 

544 

545 

546def _ALL_STAR(pack, *mods, **abspath): # PYCHOK no cover 

547 '''(INTERNAL) Mimick "for m in mods: from m import *" inside pack.__init__ 

548 returning a tuple of __all__ names collected, sorted and extended with 

549 "pack_abspath" for use in packs pyaxqg, pybelbg, pychlv and pyrdnap. 

550 ''' 

551 p = import_module(pack) # sys.modules[pack] 

552 d = p.__dict__ 

553 t = [] 

554 for m in mods: 

555 for n in m.__all__: 

556 x = getattr(m, n) 

557 if d.get(n, x) is x: 

558 d[n] = x 

559 t.append(n) 

560 else: 

561 t = '%r vs %r' % (d[n], x) 

562 raise LazyAttributeError(duplicate=n, txt=t) 

563 if abspath.get('abspath', True): 

564 t.append(_UNDER_(pack, 'abspath')) 

565 return tuple(sorted(t)) 

566 

567 

568if _FOR_DOCS: # PYCHOK no cover 

569 _ALL_DOCS = _ALL_OTHER 

570 # (INTERNAL) Only export B{C{objs.__name__}} when making the 

571 # docs to force C{epydoc} to include certain classes, methods, 

572 # functions and other names in the documentation. Using the 

573 # C{epydoc --private ...} command line option tends to include 

574 # too much internal documentation. 

575else: 

576 def _ALL_DOCS(*unused): 

577 return () 

578 

579 

580def _all_deprecates(): 

581 '''(INTERNAL) Build C{dict} of all deprecated imports and attributes. 

582 ''' 

583 D = _ALL_DEPRECATES 

584 if not D: 

585 _ALL_DEPRECATED.fill_D(D, _all_deprecates) # see _all_imports() 

586 return D 

587 

588_ALL_DEPRECATES = _Dict() # PYCHOK _ALL_DEPRECATED.imports() 

589 

590 

591def _all_enums(): 

592 '''(INTERNAL) Yield all C{(mod_, tuple)} pairs for C{__init__._all}. 

593 ''' 

594 # assert _init__all__ 

595 for mod_t in _ALL_LAZY.enums(): 

596 yield mod_t 

597 if _FOR_DOCS: 

598 for mod_t in _ALL_DEPRECATED.enums(): 

599 yield mod_t 

600 

601 

602def _all_imports(): 

603 '''(INTERNAL) Build C{dict} of all lazy imports. 

604 ''' 

605 # imports naming conventions stored below - [<key>] = <from>: 

606 # import <module> - [<module>] = <module> 

607 # from <module> import <attr> - [<attr>] = <module> 

608 # from pygeodesy import <attr> - [<attr>] = <attr> 

609 # from <module> import <attr> as <name> - [<name>] = <module>.<attr>. 

610 D = _ALL_IMPORTS 

611 if not D: 

612 _ALL_LAZY.fill_D(D, _all_imports) # see _all_deprecates() 

613 return D 

614 

615_ALL_IMPORTS = _Dict() # PYCHOK _ALL_LAZY.imports() 

616 

617 

618def _all_missing2(_all_): 

619 '''(INTERNAL) Get diffs between pygeodesy.__all__ and lazily._all_imports. 

620 ''' 

621 def _diff(one, two): 

622 return tuple(sorted(a for a in one if a not in two)) 

623 

624 _alzy = _Dict((a, a) for a in _ALL_INIT) 

625 _alzy.update(_all_imports()) # without _all_backups! 

626 return ((_DOT_(_lazily_, _all_imports.__name__), _diff(_all_, _alzy)), 

627 (_DOT_(_pygeodesy_, _DALL_), _diff(_alzy.keys(), _all_))) 

628 

629 

630def _getattras(attr_as): # test/testDeprecated 

631 '''(INTERNAL) Get the C{"as name"} or C{"name"} of a lazy entry. 

632 ''' 

633 a_, _, as_ = attr_as.partition(_asSPACED_) 

634 return as_ or a_.rstrip(_DOT_) 

635 

636 

637def _getmodattr(m, name, mod=_pygeodesy_): 

638 '''(INTERNAL) Get attr C{m.name}. 

639 ''' 

640 try: 

641 return getattr(m, name) 

642 except AttributeError: 

643 name = _DOT_(typename(m, mod), name) 

644 # <https://GitHub.com/mrJean1/PyGeodesy/issues/76> 

645 raise LazyAttributeError(_no_(_attribute_), txt=name) 

646 

647 

648def _getmodinto(mod_DNAME, *Intos): 

649 '''(INTERNAL) Core of C{_ALL_MODS.into}. 

650 ''' 

651 _MODS = _ALL_MODS 

652 mod, dun = _MODS.errors._xkwds_item2(mod_DNAME) 

653 _mod = _UNDER_(NN, mod) 

654 d = _MODS.getmodule(dun) # '__main__' OK 

655 i = _getmodattr(d, _mod, dun) 

656 assert isinstance(i, Intos) 

657 m = _MODS.getmodule(mod) 

658 setattr(d, _mod, m) # overwrite C{d._mod} 

659 if isLazy and isLazy > 1: 

660 t = _SPACE_(_HASH_, _imported_, m.__name__) # typename(m) 

661 _hash_imported(t, _MODS.into.__name__) 

662 assert getattr(d, _mod, None) is m 

663 return m 

664 

665 

666def _getmodule(name, *parent): 

667 '''(INTERNAL) Wrapper for C{import_module}. 

668 ''' 

669 try: 

670 return import_module(name, parent) 

671 except ImportError: 

672 # <https://GitHub.com/mrJean1/PyGeodesy/issues/76> 

673 raise LazyImportError(_no_(_module_), txt=name) 

674 

675 

676def _hash_imported(t, by_into, up=3): 

677 '''(INTERNAL) Helper for C{_lazy_import2} and C{_ALL_MODS.into}. 

678 ''' 

679 if isLazy and isLazy > 2: 

680 try: # see C{internals._caller3} 

681 _, f, s = _caller3(up) 

682 t = _SPACE_(t, by_into, f, _line_, s) 

683 except ValueError: 

684 pass 

685 printf(t) # XXX print 

686 

687 

688# def _lazy_attributes(DUNDER_name): 

689# '''(INTERNAL) Return a function to C{B{__name__}.__getattr__(attr)} 

690# on lazily imported modules and sub-modules. 

691# ''' 

692# if _unlazy: 

693# raise AssertionError(_COMMASPACE_(DUNDER_name, _not_(_DEPRECATED_))) 

694# 

695# def _getattr(attr, *dflt): 

696# try: # a module name 

697# return _ALL_MODS.getmodule(attr) 

698# except (AttributeError, ImportError): 

699# return _ALL_MODS.getattr(DUNDER_name, attr, *dflt) 

700# 

701# return _getattr 

702 

703 

704_lazy_dict = {} # PYCHOK overwritten by _lazy_import2 

705 

706 

707def _lazy_import2(pack): # MCCABE 14 

708 '''Check for and set up C{lazy import}. 

709 

710 @arg pack: The name of the package (C{str}) performing the imports, 

711 to help resolving relative imports, usually C{__package__}. 

712 

713 @return: 2-Tuple C{(package, getattr)} of the importing package for 

714 easy reference within itself and the callable to be set to 

715 C{package.__getattr__}. 

716 

717 @raise LazyAttributeError: The package, module or attribute name is 

718 invalid or does not exist. 

719 

720 @raise LazyImportError: Lazy import not supported or not enabled or 

721 an import failed. 

722 

723 @note: This is I{Brett Cannon}'s function U{modutil.lazy_import 

724 <https://GitHub.com/brettcannon/modutil/blob/master/modutil.py>} 

725 modified to handle the C{__all__} and C{__dir__} attributes and 

726 call C{importlib.import_module(<module>.<name>, ...)} without 

727 causing a C{ModuleNotFoundError}. 

728 

729 @see: The original U{modutil<https://PyPI.org/project/modutil>}, 

730 U{PEP 562<https://www.Python.org/dev/peps/pep-0562>} and the 

731 U{new way<https://Snarky.CA/lazy-importing-in-python-3-7/>}. 

732 ''' 

733 if pack != _pygeodesy_ or _unlazy: # Python 3.7+ # PYCHOK no cover 

734 t = _DOT_(pack, typename(_lazy_import2)) 

735 raise LazyImportError(_no_(t), txt=_versions()) 

736 

737 package, parent = _lazy_init2(pack) # _pygeodesy_ 

738 

739 _DPACKAGE_ = '__package__' 

740 _lazily_imported_ = _SPACE_(_HASH_, _lazily_, _imported_, parent) 

741 

742 sub_packages = set((parent, NN) + tuple( 

743 _DOT_(parent, s) for s in _SUB_PACKAGES)) 

744 imports = _all_imports() 

745 deprecates = _all_deprecates() 

746 

747 def __getattr__(name): # __getattr__ only for Python 3.7+ 

748 # only called once for each undefined pygeodesy attribute 

749 mod = imports.get(name, NN) or deprecates.get(name, NN) 

750 if mod: 

751 # importlib.import_module() implicitly sets sub-modules 

752 # on this module as appropriate for direct imports (see 

753 # note in the _lazy_import2.__doc__ above). 

754 if mod.endswith(_DOT_): # import mod[.attr] as name 

755 mod, _, attr = mod[:-1].rpartition(_DOT_) 

756 else: # from mod import name 

757 attr = name 

758 v = _getmodule(_DOT_(pack, mod), parent) 

759 t = getattr(v, _DPACKAGE_, None) 

760 if t not in sub_packages: # invalid module package 

761 raise LazyImportError(_DOT_(mod, _DPACKAGE_), t) 

762 if attr: # get mod.attr 

763 v = _getmodattr(v, attr, mod) 

764 

765 elif name in (_DALL_,): # XXX _Ddir_, _Dmembers_? 

766 v = _ALL_INIT + tuple(imports.keys()) 

767 else: # PYCHOK no cover 

768 t = _no_(_module_, _or_, _attribute_) 

769 # <https://GitHub.com/mrJean1/PyGeodesy/issues/76> 

770 raise LazyAttributeError(t, txt=_DOT_(parent, name)) 

771 

772 setattr(package, name, v) # package.__dict__[name] = val 

773 if isLazy > 1: 

774 t = _DOT_(_lazily_imported_, name) 

775 if mod and _tailof(mod) != name: 

776 t = _SPACE_(t, _from_, _DOT_(NN, mod)) 

777 _hash_imported(t, _by_) 

778 

779 return v # __getattr__ 

780 

781 global _lazy_dict, _lazy_module 

782 _lazy_dict = package.__dict__ 

783 _lazy_module = __getattr__ 

784 

785 return package, __getattr__ # _lazy_import2 

786 

787 

788# def _lazy_import_all(Dname): 

789# '''(INTERNAL) Return a function mimicking C{from B{__name__} import *}, 

790# of all items, see .deprecated.__init__ 

791# ''' 

792# if _unlazy: 

793# raise AssertionError(_COMMASPACE_(Dname, _not_(_DEPRECATED_))) 

794# 

795# _getattr = _lazy_attributes(Dname) # __name__.__getattr__ 

796# _import_start = _lazy_import_star(Dname, ALL_=_ALL_IMPORTS) 

797# 

798# def _import_all(attr, *dflt): 

799# return _import_star(Dname) if attr == _DALL_ else \ 

800# _getattr(attr, *dflt) 

801# 

802# return _import_all 

803 

804 

805def _lazy_import_as(DUNDER_name): 

806 '''(INTERNAL) Return a function to C{import B{__name__}.mod as mod} 

807 I{of modules only}, see .deprecated, .rhumb or get an attribute 

808 lazily exported by C{__name__}. 

809 ''' 

810 if _unlazy: 

811 return None 

812 

813 def _import_as(mod): 

814 try: 

815 return _ALL_MODS.getmodule(_DOT_(DUNDER_name, mod)) 

816 except ImportError: 

817 return _lazy_module(mod) 

818 

819 return _import_as 

820 

821 

822# def _lazy_import_star(DUNDER_name, ALL_=_ALL_DEPRECATES): 

823# '''(INTERNAL) Return a function to mimick C{from B{__name__} import *}, 

824# of all DEPRECATED items, see .deprecated, .testDeprecated 

825# ''' 

826# if _unlazy: 

827# raise AssertionError(_COMMASPACE_(DUNDER_name, _not_(_DEPRECATED_))) 

828# 

829# def _import_star(_into_): 

830# '''Do C{from B{__name__} import *} inside module C{B{__into__}}. 

831# ''' 

832# d = dict() 

833# nm = _tailof(DUNDER_name) 

834# _g = _ALL_MODS.getattr # pygeodesy.__getattr__ 

835# for a, m in ALL_.items(): 

836# if _headof(m) == nm: 

837# try: 

838# d[a] = _g(m, a) 

839# except (AttributeError, ImportError): 

840# pass 

841# _sys.modules[_into_].__dict__.update(d) 

842# return d.keys() # imported names 

843# 

844# return _import_star 

845 

846 

847def _lazy_init2(pack): 

848 '''(INTERNAL) Initialize lazy import and set globals C{isLazy} and C{_unLazy0}. 

849 

850 @arg pack: The name of the package (C{str}) performing the imports, 

851 to resolve relative imports, usually C{__package__}. 

852 

853 @return: 2-Tuple C{(package, parent)} with the importing C{package} 

854 for easy reference within itself and its name aka the 

855 C(package)'s C{parent}, same as B{C{pack}}. 

856 

857 @raise LazyImportError: Lazy import not supported or not enabled, 

858 an import failed or the package name is 

859 invalid or does not exist. 

860 

861 @note: Global C{isLazy} is set accordingly. 

862 ''' 

863 global isLazy, _unLazy0 

864 

865 E = _internals._PYGEODESY_ENV('LAZY_IMPORT') 

866 z = _internals._getenv(E, _interns._1_) # 1 default on 3.7+ 

867 z = z.strip() # like PYTHONVERBOSE et.al. 

868 isLazy = int(z) if z.isdigit() else (1 if z else 0) 

869 

870 _unLazy0 = _unlazy or not isLazy # pre-3.7 or w/o lazy import 

871 

872 if isLazy < 1: # invalid, not enabled 

873 raise LazyImportError(E, repr(z), txt_not_='enabled') 

874 if _sys.flags.verbose: # PYCHOK no cover 

875 isLazy += 1 

876 

877 try: # to initialize in Python 3+ 

878 package = import_module(pack) 

879 parent = package.__spec__.parent # __spec__ only in Python 3.7+ 

880 if parent != pack: # assert 

881 t = _COMMASPACE_(parent, _not_(pack)) # PYCHOK no cover 

882 raise AttributeError(_EQUALSPACED_('parent', t)) 

883 

884 except (AttributeError, ImportError) as x: 

885 isLazy = False # failed 

886 z = typename(_lazy_init2) 

887 raise LazyImportError(z, pack, cause=x) 

888 

889 return package, parent 

890 

891 

892def _lazy_module(name): # overwritten by _lazy_import2 

893 '''(INTERNAL) Get or import a C{pygeodesy} module. 

894 ''' 

895 try: # most likely ... module has been imported 

896 m = _ALL_MODS.getmodule(name) 

897 except (AttributeError, ImportError) as x: 

898 raise LazyImportError(name, cause=x) 

899 _lazy_dict[name] = m # cache 

900 return m 

901 

902 

903# def _lazy_subs(__name__, force=_FOR_DOCS, over=False): 

904# '''(INTERNAL) Return the names of a __name__ package's sub-packages 

905# and update the package's C{__dict__} accordingly. 

906# ''' 

907# sm = dict() 

908# if force and __name__ != _DMAIN_: 

909# nm = _tailof(__name__) 

910# _a = _ALL_MODS.getattr 

911# _m = _ALL_MODS.getmodule 

912# d = _a(__name__, _DDICT_, {}) 

913# for n in _a(__name__, _DALL_, ()): 

914# try: # n is a class name, get its mod name 

915# m = _a(__name__, n).__module__ 

916# n, s = m.split(_DOT_)[-2:] 

917# if n == nm and s not in sm: 

918# m = _m(m) # == import m as s 

919# sm[s] = m if over else d.get(s, m) 

920# except (AttributeError, ImportError, ValueError) as x: 

921# pass 

922# d.update(sm) 

923# 

924# return _ALL_OTHER(*sm.values()) 

925 

926 

927__all__ = _ALL_LAZY.lazily 

928__version__ = '26.08.18' 

929 

930if __name__ == _DMAIN_: 

931 

932 def _main(): 

933 from timeit import timeit 

934 

935 def t1(): 

936 from pygeodesy.trf import RefFrame 

937 return RefFrame 

938 

939 def t2(): 

940 return _ALL_MODS.trf.RefFrame 

941 

942 assert t1() is t2() # prime each 

943 

944 t1 = timeit(t1, number=1000000) 

945 t2 = timeit(t2, number=1000000) 

946 A = typename(_ALL_MODS) 

947 v = _versions() 

948 printf('%.6f import vs %.6f %s: %.2fX, %s', t1, t2, A, (t1 / t2), v) 

949 

950 _main() 

951 

952# % python3.15 -W ignore -m pygeodesy.lazily 

953# 0.078365 import vs 0.052132 _ALL_MODS: 1.50X, pygeodesy 26.8.18 Python 3.15.0rc1 64bit arm64 macOS 26.5.2 

954 

955# n% python3.14 -W ignore -m pygeodesy.lazily 

956# 0.064455 import vs 0.046083 _ALL_MODS: 1.40X, pygeodesy 26.8.18 Python 3.14.7 64bit arm64 macOS 26.5.2 

957 

958# % python2 -W ignore -m pygeodesy.lazily 

959# 0.685969 import vs 0.321554 _ALL_MODS: 2.13X, pygeodesy 26.8.18 Python 2.7.18 64bit arm64_x86_64 macOS 26.5.2 

960 

961# % python3.14 -W ignore -m pygeodesy.lazily 

962# 0.061219 import vs 0.047896 _ALL_MODS: 1.28X, pygeodesy 25.12.6 Python 3.14.0 64bit arm64 macOS 26.1 

963 

964# % python3.13 -W ignore -m pygeodesy.lazily 

965# 0.054235 import vs 0.052469 _ALL_MODS: 1.03X, pygeodesy 25.4.24 Python 3.13.3 64bit arm64 macOS 15.4 

966 

967# % python2 -m pygeodesy.lazily 

968# 0.653715 import vs 0.321318 _ALL_MODS: 2.03X, pygeodesy 25.4.24 Python 2.7.18 64bit arm64_x86_64 macOS 10.16 

969 

970# % python3.13 -W ignore -m pygeodesy.lazily 

971# 0.106602 import vs 0.078136 _ALL_MODS: 1.36X, pygeodesy 24.10.24 Python 3.13.0 64bit arm64 macOS 14.6.1 

972 

973# % python3.12 -W ignore -m pygeodesy.lazily 

974# 0.138844 import vs 0.080458 _ALL_MODS: 1.73X, pygeodesy 24.10.24 Python 3.12.7 64bit arm64 macOS 14.6.1 

975 

976# % python3.11 -W ignore -m pygeodesy.lazily 

977# 0.387520 import vs 0.254229 _ALL_MODS: 1.52X, pygeodesy 24.10.24 Python 3.11.5 64bit arm64 macOS 14.6.1 

978 

979# % python3.10 -W ignore -m pygeodesy.lazily 

980# 0.371269 import vs 0.272897 _ALL_MODS: 1.36X, pygeodesy 24.10.24 Python 3.10.8 64bit arm64 macOS 14.6.1 

981 

982# % python3.8 -W ignore -m pygeodesy.lazily 

983# 0.555572 import vs 0.370304 _ALL_MODS: 1.50X, pygeodesy 24.10.24 Python 3.8.10 64bit arm64_x86_64 macOS 10.16 

984 

985# % python2 -m pygeodesy.lazily 

986# 1.160292 import vs 0.490279 _ALL_MODS: 2.37X, pygeodesy 24.10.24 Python 2.7.18 64bit arm64_x86_64 macOS 10.16 

987 

988# **) MIT License 

989# 

990# Copyright (C) 2018-2026 -- mrJean1 at Gmail -- All Rights Reserved. 

991# 

992# Permission is hereby granted, free of charge, to any person obtaining a 

993# copy of this software and associated documentation files (the "Software"), 

994# to deal in the Software without restriction, including without limitation 

995# the rights to use, copy, modify, merge, publish, distribute, sublicense, 

996# and/or sell copies of the Software, and to permit persons to whom the 

997# Software is furnished to do so, subject to the following conditions: 

998# 

999# The above copyright notice and this permission notice shall be included 

1000# in all copies or substantial portions of the Software. 

1001# 

1002# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 

1003# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 

1004# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 

1005# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR 

1006# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 

1007# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 

1008# OTHER DEALINGS IN THE SOFTWARE.