Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

 

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

 

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

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

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

 

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

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

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

and later}. 

 

To disable C{lazy import}, set environment variable C{PYGEODESY_LAZY_IMPORT} 

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

each lazily imported module and attribute, similar to environment variable 

C{PYTHONVERBOSE} showing imports. Using C{3} or higher also shows the 

importing file name and line number. 

 

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

A C{lazy import} of a top-level module also loads all sub-modules 

imported by that top-level module. 

 

@var isLazy: Lazy import setting (C{int} 0, 1, 2 or 3+) from environment 

variable C{PYGEODESY_LAZY_IMPORT}, or C{None} if C{lazy import} 

is not supported or not enabled, or C{False} if initializing 

C{lazy import} failed. 

''' 

 

from copy import copy as _copy, deepcopy as _deepcopy 

from os import environ as _environ 

 

_FOR_DOCS = _environ.get('PYGEODESY_FOR_DOCS', None) 

_N_A = object() 

 

# @module_property[_RO?] <https://GitHub.com/jtushman/proxy_tools/> 

isLazy = None # see @var isLazy above 

 

 

class LazyImportError(ImportError): 

'''Lazy import is not supported, disabled or failed some other way. 

''' 

def __init__(self, fmt, *args): 

ImportError.__init__(self, (fmt % args) if args else fmt) 

 

 

class _NamedEnum_RO(dict): 

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

''' 

def __getattr__(self, attr): 

try: 

return self[attr] 

except KeyError: 

raise AttributeError("%s.%s doesn't exist" % (self._name, attr)) # PYCHOK expected 

 

def __setattr__(self, attr, value): 

raise TypeError('Read_Only %s.%s = %r' % (self._name, attr, value)) # PYCHOK expected 

 

def enums(self): 

for k, v in dict.items(self): 

if not k.startswith('_'): 

yield k, v 

 

 

def _ALL_DOCS(*names): 

'''(INTERNAL) Only export B{C{names}} when making docs to force 

C{epydoc} to include classes, methods, functions and other 

names in the documentation. Using C{epydoc --private ...} 

tends to include too much private documentation. 

''' 

return names if _FOR_DOCS else () 

 

 

_ALL_INIT = 'pygeodesy_abspath', 'version' 

 

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

_ALL_LAZY = _NamedEnum_RO(_name='_ALL_LAZY', 

bases=(), # module and for backward compatibility only 

clipy=('clipCS3', 'clipSH', 'clipSH3'), 

css=('CassiniSoldner', 'Css', 'CSSError', 'toCss'), 

datum=('R_M', 'R_MA', 'R_MB', 'R_KM', 'R_NM', 'R_SM', 'R_FM', 'R_VM', 

'Datum', 'Ellipsoid', 'Transform', 

'Datums', 'Ellipsoids', 'Transforms'), 

deprecated=('HeightIDW', 'HeightIDW2', 'HeightIDW3', 'RefFrameError', # DEPRECATED classes 

'areaof', 'bounds', 'decodeEPSG2', 'encodeEPSG', # most of the DEPRECATED functions 

'equirectangular3', 'hypot3', 'isenclosedby', 'nearestOn3', 'nearestOn4', 

'parseUTM', 'perimeterof', 'polygon', 'simplify2', 'toUtm', 'utmZoneBand2'), 

dms=('F_D', 'F_DM', 'F_DMS', 'F_DEG', 'F_MIN', 'F_SEC', 'F_RAD', 

'F_D_', 'F_DM_', 'F_DMS_', 'F_DEG_', 'F_MIN_', 'F_SEC_', 'F_RAD_', 

'F_D__', 'F_DM__', 'F_DMS__', 'F_DEG__', 'F_MIN__', 'F_SEC__', 'F_RAD__', 

'S_DEG', 'S_MIN', 'S_SEC', 'S_RAD', 'S_SEP', 

'RangeError', 'bearingDMS', 'clipDMS', 'compassDMS', 'compassPoint', 'degDMS', 'latDMS', 'lonDMS', 

'normDMS', 'parseDMS', 'parseDMS2', 'parse3llh', 'precision', 'rangerrors', 'toDMS'), 

ecef=('EcefCartesian', 'EcefError', 'EcefKarney', 'EcefMatrix', 'EcefVeness', 'EcefYou'), 

elevations=('elevation2', 'geoidHeight2'), 

ellipsoidalKarney=(), # module only 

ellipsoidalNvector=(), # module only 

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

elliptic=('Elliptic', 'EllipticError'), 

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

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

'parseETM5', 'toEtm8'), 

fmath=('EPS', 'EPS_2', 'EPS1', 'EPS1_2', 'INF', 'MANTIS', 'MAX', 'MIN', 'NAN', 'NEG0', # constants 

'Fdot', 'Fhorner', 'Fpolynomial', 'Fsum', 

'acos1', 'cbrt', 'cbrt2', 

'favg', 'fdot', 'fdot3', 'fmean', 'fhorner', 'fidw', 'fpolynomial', 'fpowers', 'fprod', 'frange', 'freduce', 'fStr', 'fStrzs', 'fsum', 'fsum_', 

'hypot', 'hypot1', 'hypot_', 'isfinite', 'isinf', 'isint', 'isnan', 'isneg0', 'isscalar', 

'len2', 'map1', 'map2', 'scalar', 'sqrt3'), 

formy=('antipode', 'bearing', 'bearing_', 'compassAngle', 'euclidean', 'euclidean_', 'equirectangular', 'equirectangular_', 

'haversine', 'haversine_', 'heightOf', 'horizon', 'isantipode', 'points2', 'vincentys', 'vincentys_'), 

frechet=('Frechet', 'FrechetDegrees', 'FrechetRadians', 'FrechetError', 

'FrechetEquirectangular', 'FrechetEuclidean', 'FrechetHaversine', 'FrechetVincentys', 

'fractional', 'frechet_'), 

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

geohash=('Geohash', 'GeohashError'), 

geoids=('GeoidError', 'GeoidG2012B', 'GeoidKarney', 'GeoidPGM', 'egmGeoidHeights', 'PGMError'), 

hausdorff=('Hausdorff', 'HausdorffDegrees', 'HausdorffRadians', 'HausdorffError', 

'HausdorffEquirectangular', 'HausdorffEuclidean', 'HausdorffHaversine', 'HausdorffKarney', 'HausdorffVincentys', 

'hausdorff_', 'randomrangenerator'), 

heights=('HeightError', 'SciPyError', 'SciPyWarning', 

'HeightIDWequirectangular', 'HeightIDWeuclidean', 'HeightIDWhaversine', 'HeightIDWkarney', 'HeightIDWvincentys', 

'HeightCubic', 'HeightLinear', 'HeightLSQBiSpline', 'HeightSmoothBiSpline'), 

lazily=('LazyImportError', 'isLazy'), 

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

mgrs=('Mgrs', 'MGRSError', 'parseMGRS', 'toMgrs'), 

named=('classname', 'classnaming', 'inStr', 'nameof'), 

nvector=(), # module and for backward compatibility only 

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

points=('LatLon_', 'LatLon2psxy', 'Numpy2LatLon', 'Tuple2LatLon', 

'areaOf', 'boundsOf', 'centroidOf', 

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

'nearestOn5', 'perimeterOf'), 

sphericalNvector=(), # module only 

sphericalTrigonometry=(), # module only 

simplify=('simplify1', 'simplifyRDP', 'simplifyRDPm', 'simplifyRW', 'simplifyVW', 'simplifyVWm'), 

trf=('RefFrame', 'RefFrames', 'TRFError', 'date2epoch'), 

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

utily=('OK', 'PI', 'PI2', 'PI_2', 'PI_4', 'R_M', 'LimitError', 

'anStr', 'clipStr', 

'degrees', 'degrees90', 'degrees180', 'degrees360', 'degrees2m', 

'enStr2', 'false2f', 'ft2m', 'halfs2', 

'isNumpy2', 'isPoints2', 'issequence', 'issubclassof', 'isTuple2', 'iterNumpy2', 'iterNumpy2over', 

'limiterrors', 'm2degrees', 'm2ft', 'm2km', 'm2NM', 'm2SM', 

'property_RO', 

'radians', 'radiansPI', 'radiansPI2', 'radiansPI_2', 

'sincos2', 'sincos2d', 'splice', 'tan_2', 'tanPI_2_2', 

'unroll180', 'unrollPI', 'unStr', 

'wrap90', 'wrap180', 'wrap360', 'wrapPI_2','wrapPI', 'wrapPI2'), 

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

utmups=('UtmUps', 'UTMUPSError', 'parseUTMUPS5', 'toUtmUps8', 'utmupsValidate', 'utmupsValidateOK', 'utmupsZoneBand5'), 

vector3d=('CrossError', 'crosserrors', 'VectorError'), # nothing else 

webmercator=('Wm', 'WebMercatorError', 'parseWM', 'toWm'), 

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

 

# DEPRECATED __all__ names overloading those in _ALL_LAZY.deprecated where 

# the new name is fully backward compatible in signature and return value 

_ALL_OVERRIDING = _NamedEnum_RO(_name='_ALL_OVERRIDING', # all DEPRECATED 

fmath=('hypot_ as hypot3',), 

formy=('points2 as polygon',), 

heights=('HeightIDWequirectangular as HeightIDW2', 'HeightIDWeuclidean as HeightIDW', 'HeightIDWhaversine as HeightIDW3'), 

points=('areaOf as areaof', 

'isenclosedBy as isenclosedby', 'perimeterOf as perimeterof'), 

simplify=('simplifyRW as simplify2',)) 

 

__all__ = _ALL_LAZY.lazily 

__version__ = '20.01.23' 

 

 

def _all_imports(**more): 

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

''' 

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

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

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

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

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

imports = {} 

for _all_ in (_ALL_LAZY, _ALL_OVERRIDING, more): 

for mod, attrs in _all_.items(): 

if isinstance(attrs, tuple) and not mod.startswith('_'): 

if mod not in imports: 

imports[mod] = mod 

elif imports[mod] != mod: 

raise AssertionError('%s[%r] vs %r' % ('imports', 

imports[mod], mod)) 

for attr in attrs: 

attr, _, _as_ = attr.partition(' as ') 

if _as_: 

imports[_as_] = mod + '.' + attr 

else: 

imports[attr] = mod 

return imports 

 

 

def _all_missing2(_all_): 

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

''' 

_alzy = _all_imports(**_NamedEnum_RO((a, ()) for a in _ALL_INIT)) 

return (('lazily._all_imports', ', '.join(a for a in _all_ if a not in _alzy)), 

('pygeodesy.__all__', ', '.join(a for a in _alzy if a not in _all_))) 

 

 

def _2kwds(kwds, **dflts): 

'''(INTERNAL) Override C{dflts} with C{kwds}. 

''' 

d = dflts 

if kwds: 

d = d.copy() 

d.update(kwds) 

return d 

 

 

def _lazy_import2(_package_): # MCCABE 23 

'''Check for and set up lazy importing. 

 

@param _package_: The name of the package (C{str}) performing 

the imports, to help facilitate resolving 

relative imports. 

 

@return: 2-Tuple (package, getattr) of the importing package for 

easy reference within itself and the callable to be set 

to `__getattr__`. 

 

@raise LazyImportError: Lazy import not supported, an import 

failed or a module name or attribute 

name is invalid or does not exist. 

 

@note: This is the original function U{modutil.lazy_import 

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

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

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

without causing a C{ModuleNotFoundError}. 

 

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

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

U{Werkzeug<https://GitHub.com/pallets/werkzeug/blob/master/werkzeug/__init__.py>}. 

''' 

global isLazy 

 

import sys 

if sys.version_info[:2] < (3, 7): # not supported 

raise LazyImportError('no %s.%s for Python %s', _package_, 

_lazy_import2.__name__, sys.version.split()[0]) 

 

z = _environ.get('PYGEODESY_LAZY_IMPORT', None) 

if z is None: # PYGEODESY_LAZY_IMPORT not set 

isLazy = 1 # on by default on 3.7 

else: 

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

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

if isLazy < 1: # not enabled 

raise LazyImportError('env %s=%r', 'PYGEODESY_LAZY_IMPORT', z) 

if _environ.get('PYTHONVERBOSE', None): 

isLazy += 1 

del z 

 

try: # to initialize 

from importlib import import_module 

 

package = import_module(_package_) 

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

if parent != _package_: # assertion 

raise AttributeError('parent %r vs %r' % (parent, _package_)) 

except (AttributeError, ImportError) as x: 

isLazy = False # failed 

raise LazyImportError('init failed: %s', x) 

 

if isLazy > 2: # trim import path names 

import os # PYCHOK re-import 

cwdir = os.getcwd() 

cwdir = cwdir[:-len(os.path.basename(cwdir))] 

del os 

else: # no import path names 

cwdir = '' 

 

import_ = _package_ + '.' # namespace 

imports = _all_imports() 

 

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

# only called once for each undefined pygeodesy attribute 

if name in imports: 

# importlib.import_module() implicitly sets sub-modules 

# on this module as appropriate for direct imports (see 

# note in the _lazy_import.__doc__ above). 

mod, _, attr = imports[name].partition('.') 

if mod not in imports: 

raise LazyImportError('no %s %s.%s', 'module', parent, mod) 

imported = import_module(import_ + mod, parent) # XXX '.' + mod 

if imported.__package__ not in (parent, '__main__', ''): 

raise LazyImportError('%s.%s %r' % (mod, '__package__', imported.__package__)) 

# import the module or module attribute 

if attr: 

imported = getattr(imported, attr, _N_A) 

elif name != mod: 

imported = getattr(imported, name, _N_A) 

if imported is _N_A: 

raise LazyImportError('no %s %s.%s', 'attribute', mod, attr or name) 

 

elif name in ('__all__',): # XXX '__dir__', '__members__'? 

imported = _ALL_INIT + tuple(imports.keys()) 

mod = '' 

else: 

raise LazyImportError('no %s %s.%s', 'module or attribute', parent, name) 

 

setattr(package, name, imported) 

if isLazy > 1: 

z = '' 

if mod and mod != name: 

z = ' from .%s' % (mod,) 

if isLazy > 2: 

# sys._getframe(1) ... 'importlib._bootstrap' line 1032, 

# may throw a ValueError('call stack not deep enough') 

try: 

f = sys._getframe(2) # importing file and line 

n = f.f_code.co_filename 

if cwdir and n.startswith(cwdir): 

n = n[len(cwdir):] 

z = '%s by %s line %d' % (z, n, f.f_lineno) 

except ValueError: 

pass 

print('# lazily imported %s.%s%s' % (parent, name, z)) 

 

return imported # __getattr__ 

 

return package, __getattr__ # _lazy_import2 

 

 

def _xcopy(inst, deep=False): 

'''(INTERNAL) Copy an instance, shallow or deep. 

 

@param inst: The instance to copy (C{_Named}). 

@keyword deep: If C{True} make a deep, otherwise 

shallow copy (C{bool}). 

 

@return: The copy (C{This class} or subclass thereof). 

''' 

return _deepcopy(inst) if deep else _copy(inst) 

 

# **) MIT License 

# 

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

# 

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

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

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

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

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

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

# 

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

# in all copies or substantial portions of the Software. 

# 

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

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

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

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

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

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

# OTHER DEALINGS IN THE SOFTWARE.