Debian Codegraph @

gavo/utils/codetricks.py

raw
1 """
2 Functions dealing with compilation and introspection of python and
3 external code.
4 """
5
6 #c Copyright 2008-2025, the GAVO project <[email protected]>
7 #c
8 #c This program is free software, covered by the GNU GPL. See the
9 #c COPYING file in the source distribution.
10
11
12 from __future__ import annotations
13
14 import ast
15 import atexit
16 import contextlib
17 import importlib.util
18 import io
19 import itertools
20 import inspect
21 import functools
22 import linecache
23 import os
24 import re
25 import shutil
26 import sys
27 import tempfile
28 import threading
29 import weakref
30
31 from gavo.utils import algotricks
32 from gavo.utils import misctricks
33 from gavo.utils import excs
34
35 from gavo.utils.dachstypes import (Any, Callable, Dict, Filename,
36 Generator, Hashable, List, ModuleType, Optional,
37 Sequence, Set, StrToStrMap, TextIO, Tuple, TypeVar, TYPE_CHECKING)
38
39 if TYPE_CHECKING:
40 T = TypeVar("T")
41
42 def document(origFun: Any):
43 """is a decorator that adds a "buildDocsForThis" attribute to its argument.
44
45 This attribute is evaluated by documentation generators.
46 """
47 origFun.buildDocsForThis = True
48 return origFun
49
50
51 class CachedGetter:
52 """A cache for a callable.
53
54 This is basically memoization, except that these are supposed
55 to be singletons; CachedGetters should be used where the
56 construction of a resource (e.g., a grammar) should be deferred
57 until it is actually needed to save on startup times.
58
59 The resource is created on the first call, all further calls
60 just return references to the original object.
61
62 You can also leave out the getter argument and add an argumentless
63 method impl computing the value to cache.
64
65 Using a CachedGetter also serializes generation, so you can also
66 use it when getter isn't thread-safe.
67
68 At construction, you can pass a f(thing) -> bool in an isAlive
69 keyword argument. If you do, the function will be called with the
70 cache before the cache is being returned. If it returns false,
71 the resource is re-made (no concurrency control is enforced here).
72 """
73 def __init__(self, getter: Callable, *args, **kwargs):
74 if getter is None:
75 getter = self.impl
76 self.cache: Any = None
77 self.getter = getter
78
79 self.isAlive: Optional[Callable[[Any], bool]
80 ] = kwargs.pop("isAlive", None)
81 self.args, self.kwargs = args, kwargs
82 self.lock = threading.Lock()
83
84 def __call__(self):
85 if (self.isAlive is not None
86 and self.cache is not None
87 and not self.isAlive(self.cache)):
88 self.cache = None
89
90 if self.cache is None:
91 with self.lock:
92 # Second and following in already have the cache set and return here
93 if self.cache is not None:
94 return self.cache
95 self.cache = self.getter(*self.args, **self.kwargs)
96
97 # If the cache is immortal, do away with the stuff needed
98 # for its creation
99 if self.isAlive is None:
100 del self.args
101 del self.kwargs
102 del self.lock
103
104 return self.cache
105
106
107 class DeferredImport:
108 """A trivial deferred module loader.
109
110 Use this to delay the actual import of a module until it's actually
111 needed.
112
113 It is constructed with a module name (that will be inserted into the
114 calling module's globals() as a side effect) and some literal code
115 that, when executed in the caller's global namespace, actually
116 imports the module, for instance::
117
118 utils.DeferredImport("wcs", "from astropy import wcs")
119
120 As a service for static code checking, you'll usually want to repeat
121 the module name, though::
122
123 wcs = utils.DeferredImport("wcs", "from astropy import wcs")
124 """
125 loadedModule = None
126
127 def __init__(self, moduleName: str, loadingCode:str):
128 # I now f_back is non-None here, so silence mypy
129 self.parentGlobals = inspect.currentframe().f_back.f_globals # type: ignore
130 self.moduleName = moduleName
131 self.loader = compile(loadingCode, "<modloader-%s>"%id(self), 'exec')
132 self.parentGlobals[moduleName] = self
133
134 def __getattr__(self, name: str):
135 exec(self.loader, self.parentGlobals)
136 return getattr(self.parentGlobals[self.moduleName], name)
137
138
139 class IdManagerMixin:
140 """
141 A mixin for objects requiring unique IDs.
142
143 The primary use case is XML generation, where you want stable IDs
144 for objects, but IDs must be unique over an entire XML file.
145
146 The IdManagerMixin provides some methods for doing that:
147
148 - makeIdFor(object) -- returns an id for object, or None if makeIdFor has
149 already been called for that object (i.e., it presumably already is
150 in the document).
151
152 - getIdFor(object) -- returns an id for object if makeIdFor has already
153 been called before. Otherwise, a NotFoundError is raised
154
155 - getOrMakeIdFor(object) -- returns an id for object; if object has
156 been seen before, it's the same id as before. Identity is by equality
157 for purposes of dictionaries.
158
159 - getForId(id) -- returns the object belonging to an id that has
160 been handed out before. Raises a NotFoundError for unknown ids.
161
162 - cloneFrom(other) -- overwrites the self's id management dictionaries
163 with those from other. You want this if two id managers must work
164 on the same document.
165 """
166 __cleanupPat = re.compile("[^A-Za-z0-9_]+")
167 # Return a proxy instead of raising a KeyError here? We probably do not
168 # really want to generate xml with forward references, but who knows?
169 def __getIdMaps(self) -> Tuple[Dict, Dict]:
170 try:
171 return self.__objectToId, self.__idsToObject
172 except AttributeError:
173 self.__objectToId: Dict[Hashable, str] = {}
174 self.__idsToObject: Dict[str, Hashable] = {}
175 return self.__objectToId, self.__idsToObject
176
177 def _fixSuggestion(self, suggestion: str, invMap: StrToStrMap
178 ) -> str:
179 """returns suggestion with some suffix to make in unique if it not
180 already is.
181 """
182 for i in itertools.count(start=2):
183 newId = f"{suggestion}-{i:02d}"
184 if newId not in invMap:
185 return newId
186 return suggestion # notreached
187
188 def cloneFrom(self, other):
189 """takes the id management dictionaries from other.
190 """
191 self.__objectToId, self.__idsToObject = other.__getIdMaps()
192
193 def makeIdFor(self, ob: Hashable, suggestion: Optional[str]=None
194 ) -> str:
195 """returns a new id for ob (which must be Hashable).
196
197 suggestion can be a string giving what id ought to be; the function
198 will change it as necessary to make it a usable and unique id.
199
200 If the object already has an id, the method will raise a ValueError
201 (since DaCHS 2.8.1; returned None before).
202 """
203 map, invMap = self.__getIdMaps()
204 if suggestion:
205 suggestion = self.__cleanupPat.sub("", suggestion)
206 if id(ob) in map:
207 raise ValueError(f"{ob} already has the id {id(ob)}")
208
209 if suggestion is not None:
210 if suggestion in invMap:
211 newId = self._fixSuggestion(suggestion, invMap)
212 else:
213 newId = suggestion
214 else:
215 newId = intToFunnyWord(id(ob))
216
217 # register id(ob) <-> newId map, avoiding refs to ob
218 map[id(ob)] = newId
219 try:
220 invMap[newId] = weakref.proxy(ob)
221 except TypeError: # something we can't weakref to
222 invMap[newId] = ob
223 return newId
224
225 def getIdFor(self, ob: Hashable) -> str:
226 """returns the id for ob if it is known.
227
228 If ob does not yet have an id, the method raises a NotFoundError.
229 """
230 try:
231 return self.__getIdMaps()[0][id(ob)]
232 except KeyError:
233 raise excs.NotFoundError(repr(ob), what="object",
234 within="id manager %r"%(self,), hint="Someone asked for the"
235 " id of an object not managed by the id manager. This usually"
236 " is a software bug.")
237
238 def getOrMakeIdFor(self,
239 ob: Hashable, suggestion: Optional[str]=None) -> str:
240 """returns the id of the (hashable) ob or creates one if it
241 does not already have one.
242
243 This is the function you would normally use with the id manager.
244 """
245 try:
246 return self.getIdFor(ob)
247 except excs.NotFoundError:
248 return self.makeIdFor(ob, suggestion)
249
250 def getForId(self, id: str) -> Hashable:
251 """returns the object associated with id.
252
253 This will raise a KeyError for unknown ids.
254 """
255 try:
256 return self.__getIdMaps()[1][id]
257 except KeyError:
258 raise excs.NotFoundError(id, what="id", within="id manager %r"%(self,),
259 hint="Someone asked for the object belonging to an id that has"
260 " been generated externally (i.e., not by this id manager). This"
261 " usually is an internal error of the software.")
262
263
264 class NullObject(object):
265 """A Null object, i.e. one that accepts any method call whatsoever.
266
267 This mainly here for use in scaffolding.
268 """
269 def __getattr__(self, name: str):
270 return self
271
272 def __call__(self, *args, **kwargs):
273 pass
274
275
276 class _CmpType(type):
277 """is a metaclass for *classes* that always compare in one way.
278 """
279 # Ok, the class thing is just posing. It's fun anyway.
280 def __lt__(cls, other):
281 return cls.cmpRes
282
283 def __le__(cls, other):
284 return cls.cmpRes
285
286 def __gt__(cls, other):
287 return not cls.cmpRes
288
289 def __ge__(cls, other):
290 return not cls.cmpRes
291
292 def __eq__(cls, other):
293 return False
294
295
296 class _Comparer(object, metaclass=_CmpType):
297 def __init__(self, *args, **kwargs):
298 raise excs.Error(
299 "%s classes can't be instantiated."%self.__class__.__name__)
300
301
302 class Infimum(_Comparer):
303 """is a *class* smaller than anything.
304
305 This will only work as the first operand.
306
307 >>> Infimum<-2333
308 True
309 >>> Infimum<""
310 True
311 >>> -2333<Infimum
312 False
313 """
314 cmpRes = True
315
316
317 class Supremum(_Comparer):
318 """is a *class* larger than anything.
319
320 This will only work as the first operand.
321
322 >>> Supremum>1e300
323 True
324 >>> Supremum>""
325 True
326 >>> Supremum>None
327 True
328 >>> Supremum>Supremum
329 True
330 """
331 cmpRes = False
332
333
334 class AllEncompassingSet(set):
335 """a set that contains everything.
336
337 Ok, so this doesn't exist. Yes, I've read my Russell. You see, this
338 is a restricted hack for a reason. And even the docstring is
339 contradictory.
340
341 Sort-of. This now works for intersection and containing.
342 Should this reject union? Also, unfortunately this only works as a
343 left operand; I don't see how to override whatever set does with
344 this as a right operand.
345
346 >>> s = AllEncompassingSet()
347 >>> s & set([1,2])
348 {1, 2}
349 >>> "gooble" in s
350 True
351 >>> s in s
352 True
353 >>> s not in s
354 False
355 """
356 def __init__(self):
357 set.__init__(self, [])
358
359 def __bool__(self):
360 return True
361
362 # I don't want to mimic the complex signature of the superclass
363 # here, so let's shut mypy up.
364 def __and__(self, other: Set) -> Set: # type: ignore
365 return other
366
367 def intersection(self, other: Set) -> Set: # type: ignore
368 return other
369
370 def __contains__(self, el: Any):
371 return True
372
373
374 def iterDerivedClasses(baseClass: type, objects: List[Any]):
375 """iterates over all subclasses of baseClass in the sequence objects.
376 """
377 for cand in objects:
378 try:
379 if issubclass(cand, baseClass) and cand is not baseClass:
380 yield cand
381 except TypeError: # issubclass wants a class
382 pass
383
384
385 def iterDerivedObjects(baseClass: type, objects: List[Any]):
386 """iterates over all instances of baseClass in the sequence objects.
387 """
388 for cand in objects:
389 if isinstance(cand, baseClass):
390 yield cand
391
392
393 # The API of buildClassResolver is a bit painful because it
394 # can actually instantiate the classes. That's why there's an
395 # Any in the signature; this would be a good place for overload
396 # (or to separate the two functions).
397 def buildClassResolver(
398 baseClass: type,
399 objects: List[Any],
400 instances: bool=False,
401 key: Callable[[Hashable], Optional[str]]
402 =lambda obj: getattr(obj, "name", None),
403 default=None
404 ) -> Callable[[str], Any]:
405 """returns a function resolving classes deriving from baseClass
406 in the sequence objects by their names.
407
408 This is used to build registries of, for instance, Macros and RowProcessors.
409 The classes in question have to have a name attribute.
410
411 objects would usually be something like globals().values()
412
413 If instances is True the function will return instances instead
414 of classes.
415
416 key is a function taking an object and returning the key under which
417 you will later access it. If this function returns None, the object
418 will not be entered into the registry.
419 """
420 if instances:
421 registry: Dict[str, Any] = algotricks.DeferringDict()
422 else:
423 registry = {}
424
425 for cls in iterDerivedClasses(baseClass, objects):
426 clsKey = key(cls)
427 if clsKey is not None:
428 registry[clsKey] = cls
429
430 def resolve(name:str, registry: Dict[str, Any]=registry):
431 try:
432 return registry[name]
433 except KeyError:
434 if default is not None:
435 return default
436 raise
437
438 # see mypy bug #2087
439 resolve.registry = registry # type: ignore
440 return resolve
441
442
443 _SILENCE_LOCK = threading.RLock()
444
445 @contextlib.contextmanager
446 def silence(errToo: bool=False) -> Generator:
447 """a context manager to temporarily redirect stdout to /dev/null.
448
449 This is used to shut up some versions of pyparsing and pyfits that
450 insist on spewing stuff to stdout from deep within in relatively
451 normal situations.
452
453 Note that this will acquire a lock while things are silenced; this
454 means that silenced things cannot run concurrently.
455 """
456 with _SILENCE_LOCK:
457 realstdout = sys.stdout
458 sys.stdout = devnull()
459 if errToo:
460 realstderr = sys.stderr
461 sys.stderr = sys.stdout
462
463 try:
464 yield
465 finally:
466 sys.stdout.close()
467 sys.stdout = realstdout
468 if errToo:
469 sys.stderr = realstderr
470
471
472 @contextlib.contextmanager
473 def in_dir(destDir: Filename) -> Generator:
474 """executes the controlled block within destDir and then returns
475 to the previous directory.
476
477 Think "within dir". Haha.
478 """
479 owd = os.getcwd()
480 os.chdir(destDir)
481 try:
482 yield owd
483 finally:
484 os.chdir(owd)
485
486
487 @contextlib.contextmanager
488 def sandbox(
489 tmpdir: Optional[Filename]=None,
490 debug: Optional[bool]=False,
491 extractfunc: Optional[Callable[[Filename], None]]=None):
492 """sets up and tears down a sandbox directory within tmpdir.
493
494 This is is a context manager. The object returned is the original
495 path (which allows you to copy stuff from there). The working
496 directory is the sandbox created while in the controlled block.
497
498 If tmpdir is None, the *system* default is used (usually /tmp),
499 rather than dachs' tmpdir. So, you will usually want to call
500 this as sandbox(base.getConfig("tempDir"))
501
502 This is obviously not thread-safe -- you'll not usually want
503 to run this in the main server process. Better fork before
504 running this.
505
506 You can pass in a function extractfunc(owd) that is executed in
507 the sandbox just before teardown. It receives the original working
508 directory and can, e.g., move files there from the sandbox.
509 """
510 owd = os.getcwd()
511 wd = tempfile.mkdtemp("sandbox", dir=tmpdir)
512 os.chdir(wd)
513 try:
514 yield owd
515 finally:
516 try:
517 if extractfunc:
518 extractfunc(owd)
519 except Exception as ex:
520 sys.stderr.write("Extraction function failed: %s\n"%ex)
521
522 os.chdir(owd)
523 if not debug:
524 shutil.rmtree(wd)
525
526
527 def _instrumentForDebugging(func: Callable, funcName: str, src: str
528 ) -> Callable:
529 """returns a callable for a callable func with instrumentation for
530 debugging.
531
532 src must be the source of func.
533
534 Specifically, when there's an exception when calling func, this will
535 be logged as a warning.
536 """
537 debugLocals: Dict[str, Any] = {}
538 embSrc = "\n".join([
539 "from gavo.utils import excs",
540 "def compileFunctionDebugWrapper(*args, **kwargs):",
541 " try:",
542 " return %s(*args, **kwargs)"%funcName,
543 " except (excs.ExecutiveAction, AssertionError):",
544 " raise",
545 " except:",
546 ' notify("Failing source:\\n%s"%src)',
547 " raise"])
548 debugLocals["src"] = src
549 debugLocals["notify"] = lambda msg: misctricks.sendUIEvent("Warning", msg)
550 debugLocals[funcName] = func
551 exec(embSrc+"\n", debugLocals)
552 return debugLocals["compileFunctionDebugWrapper"]
553
554
555 # What with function attributes, wild lambdas and the linecache,
556 # it's nigh impossible to satisfy mypy on this:
557 def compileFunction(src: str,
558 funcName: str,
559 useGlobals: Optional[Dict[str, Any]]=None,
560 debug: bool=False,
561 uniqueName: Optional[str]=None):
562 """runs src through exec and returns the funcName from the resulting
563 namespace.
564
565 This takes care to preserve src in the line cache so it is available
566 in tracebacks or in the debugger.
567
568 useGlobals can be a namespace; if not passed, the globals of the
569 utils.codestricks is used.
570
571 If debug=True is passed in, additional code is produced to give halfway
572 useful tracebacks.
573
574 uniqueName, if given, is the identifier for the code. If passed in,
575 no automatic cleanup for the linecache is done under the assumption
576 that reloads (or whatever) will overwrite the linecache. Otherwise
577 code is autonumbered (which is not really desirable for user-provided
578 code, as they won't know where their failing code comes from).
579
580 This is typically used to define functions, like this:
581
582 >>> resFunc = compileFunction("def f(x): print(x)", "f")
583 >>> resFunc(1); resFunc("abc")
584 1
585 abc
586 """
587 if not hasattr(compileFunction, "autoNumber"):
588 compileFunction.autoNumber = 0 # type: ignore
589
590 doCleanup = False
591 if uniqueName is None:
592 uniqueName = "<generated code %s>"%compileFunction.autoNumber # type: ignore
593 compileFunction.autoNumber += 1 # type: ignore
594 doCleanup = True
595 if uniqueName in linecache.cache:
596 # this is particularly insiduous with active tags
597 for i in itertools.count():
598 if f"{uniqueName}-{i}" not in linecache.cache:
599 uniqueName = f"{uniqueName}-{i}"
600 break
601
602 src = src+"\n"
603 localVars: Dict[str, Any] = {}
604 if useGlobals is None:
605 useGlobals = globals()
606
607 try:
608 code = compile(src, uniqueName, 'exec')
609 exec(code, useGlobals, localVars)
610 except Exception as ex:
611 misctricks.sendUIEvent("Warning", "The code that failed to compile was:"
612 "\n%s"%src)
613 raise misctricks.logOldExc(excs.BadCode(src, "function", ex))
614 func = localVars[funcName]
615
616 # this makes our compiled lines available to the traceback writer.
617 # we might want to do sys.excepthook = traceback.print_exception
618 # somewhere so the post mortem dumper uses this, too. Let's see
619 # if it's worth the added risk of breaking things.
620 linecache.cache[uniqueName] = ( # type: ignore
621 len(src), None, src.split("\n"), uniqueName)
622 if doCleanup:
623 func._cleanup = weakref.ref(func,
624 lambda _, key=uniqueName: linecache and linecache.cache.pop(key, None)) #type: ignore
625
626 if debug:
627 return _instrumentForDebugging(func, funcName, src)
628 else:
629 return func
630
631
632 def ensureExpression(expr: str, errName: str="unknown") -> None:
633 """raises a LiteralParserError if expr is not a parseable python expression.
634
635 >>> ensureExpression("4+4")
636 >>> ensureExpression("'/'.join([str(x) for x in range(10)])")
637 >>> ensureExpression("junk")
638 """
639 try:
640 tree = ast.parse(expr)
641 except SyntaxError as msg:
642 raise misctricks.logOldExc(excs.BadCode(expr, "expression", msg))
643 # An ast for an expression is a Discard inside at Stmt inside the
644 # top-level Module
645 try:
646 exprNodes = tree.body
647 if len(exprNodes)!=1:
648 raise ValueError("Not a single statement")
649 if not isinstance(exprNodes[0], ast.Expr):
650 raise ValueError("Not an expression")
651 except (ValueError, AttributeError) as ex:
652 raise misctricks.logOldExc(excs.BadCode(expr, "expression", ex))
653
654
655 def importModule(modName: str) -> ModuleType:
656 """imports a module from the module path.
657
658 Use this to programmatically import "normal" modules, e.g., dc-internal
659 ones. It uses python's standard import mechanism and returns the
660 module object.
661
662 We're using exec and python's normal import, so the semantics
663 should be identical to saying import modName except that the
664 caller's namespace is not changed.
665
666 The function returns the imported module.
667 """
668 # ward against exploits (we're about to use exec): check syntax
669 if not re.match(r"([A-Za-z_]+)(\.[A-Za-z_]+)*", modName):
670 raise excs.Error("Invalid name in internal import: %s"%modName)
671 parts = modName.split(".")
672 vars: Dict[str, Any] = {}
673 if len(parts)==1:
674 exec("import %s"%modName, vars)
675 else:
676 exec("from %s import %s"%(".".join(parts[:-1]), parts[-1]), vars)
677 return vars[parts[-1]]
678
679
680 @document
681 def loadPythonModule(fqName: Filename, relativeTo: Optional[Filename]=None
682 ) -> Tuple[ModuleType, Any]:
683 """imports fqName and returns the (module, spec).
684
685 Do not use this function to import DC-internal modules; this may
686 mess up singletons since you could bypass python's mechanisms
687 to prevent multiple imports of the same module.
688
689 fqName is a fully qualified path to the module without the .py,
690 unless relativeTo is given, in which case it is interpreted as a
691 relative path. This for letting modules in resdir/res import each
692 other by saying::
693
694 mod, _ = api.loadPythonModule("foo", relativeTo=__file__)
695
696 The python path is temporarily amended with the path part of the
697 source module.
698
699 If the module is in /var/gavo/inputs/foo/bar/mod.py, Python will know
700 the module as foo_bar_mod (the last two path components are always added).
701 This is to keep Python from using the module when someone writes
702 import mod.
703 """
704 fqName = str(fqName)
705 if relativeTo is not None:
706 fqName = os.path.join(os.path.dirname(relativeTo), fqName)
707
708 try:
709 spec = importlib.util.spec_from_file_location(
710 "_".join(fqName.split("/")[-3:]),
711 fqName+".py")
712 if spec is None:
713 raise ImportError("Could not locate or open %s"%fqName)
714
715 module = importlib.util.module_from_spec(spec)
716 except ImportError:
717 # cloak the actual import error; since this probably comes from user
718 # code, chances are they want to see something else. Let's guess a
719 # structure error
720 raise excs.StructureError("Requested module %s not importable."%fqName,
721 hint="If it exists at all, the import might also fail because"
722 ' of syntax errors or similar. Try python -c "import mod" to get'
723 ' a clue in that case.')
724
725 spec.loader.exec_module(module) # type: ignore
726
727 return module, spec
728
729
730 def loadInternalObject(relativeName: str, objectName: str) -> Any:
731 """gets a name from an internal module.
732
733 relativeName is the python module path (not including "gavo."),
734 objectName the name of something within the module.
735
736 This is used for "manual" registries (grammars, cores,...).
737 """
738 modName = "gavo."+relativeName
739 module = importModule(modName)
740 return getattr(module, objectName)
741
742
743 def memoized(origFun: Callable):
744 """a trivial memoizing decorator.
745
746 This is a legacy wrapper for functools.lru_cache. Don't use in new
747 code
748 """
749 return functools.lru_cache()(origFun)
750
751
752 def iterConsecutivePairs(sequence: Sequence):
753 """yields pairs of consecutive items from sequence.
754
755 If the last item cannot be paired, it is dropped.
756
757 >>> list(iterConsecutivePairs(range(6)))
758 [(0, 1), (2, 3), (4, 5)]
759 >>> list(iterConsecutivePairs(range(5)))
760 [(0, 1), (2, 3)]
761 """
762 iter1, iter2 = iter(sequence), iter(sequence)
763 next(iter2)
764 return list(zip(
765 itertools.islice(iter1, None, None, 2),
766 itertools.islice(iter2, None, None, 2)))
767
768
769 def iterRanges(separators: Sequence[T]) -> Generator[Tuple[T, T], None, None]:
770 """yields (left, right) pairs for a sequence of separating indexes.
771
772 This is when you want to partition a sequence based on cut points.
773
774 >>> list(iterRanges(range(6)))
775 [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
776 """
777 i = iter(separators)
778 left = next(i)
779 for right in i:
780 yield left, right
781 left = right
782
783
784 def identity(x: Any) -> Any:
785 return x
786
787
788 def intToFunnyWord(anInt: int, translation=bytes.maketrans(
789 b"-0123456789abcdef",
790 b"zaeiousmnthwblpgd")) -> str:
791 """returns a sometimes funny (but unique) byte string from an arbitrary
792 integer.
793
794 >>> intToFunnyWord(3829901938)
795 'guunwwni'
796 """
797 return (b"%x"%anInt).translate(translation).decode("ascii")
798
799
800 def addDefaults(dataDict: Dict, defaultDict: Dict) -> None:
801 """adds key-value pairs from defaultDict to dataDict if the key is missing
802 in dataDict.
803 """
804 for key, value in defaultDict.items():
805 if key not in dataDict:
806 dataDict[key] = value
807
808
809 @functools.lru_cache(None)
810 def devnull() -> TextIO:
811 """returns a (string-) writable /dev/null.
812
813 This always returns the same object, and to placate resource warnings,
814 the file will be closed before exiting the program; the close method
815 of the returned thing is a no-op.
816 """
817 devnull = open("/dev/null", "w")
818 closeIt = devnull.close
819 devnull.close = lambda: None # type: ignore
820 atexit.register(closeIt)
821 return devnull
822
823
824 def memoizeOn(
825 onObject: object,
826 generatingObject: object,
827 generatingFunction: Callable,
828 *args) -> Any:
829 """memoizes the result of generatingFunction on onObject and returns it.
830
831 This is for caching things that adapt to onObjects; see procdefs
832 and rowmakers for examples why this is useful.
833
834 args is passed to generatingFunction; generatingObject is only
835 needed for identification.
836 """
837 cacheName = "_cache%s%s"%(generatingObject.__class__.__name__,
838 str(id(generatingObject)))
839 if getattr(onObject, cacheName, None) is None:
840 setattr(onObject, cacheName, generatingFunction(*args))
841 return getattr(onObject, cacheName)
842
843
844 def forgetMemoized(ob: object) -> None:
845 """clears things memoizeOn-ed on ob or @utils.memoize-ed.
846
847 This is sometimes necessary to let the garbage collector free
848 ob, e.g., when closures have been memoized.
849 """
850 for n in dir(ob):
851 child = getattr(ob, n)
852 # this is for @memoized things
853 if hasattr(child, "_cache"):
854 child._cache.clear()
855
856 # this is for lru_cache-decorated functions
857 if hasattr(child, "cache_clear"):
858 child.cache_clear()
859
860 # this is for memoizedOn-ed things
861 if n.startswith("_cache"):
862 delattr(ob, n)
863
864
865 def stealVar(varName: str) -> Any:
866 """returns the first local variable called varName in the frame stack
867 above my caller.
868
869 This is obviously abominable. This is only used within the DC code where
870 the author deemed the specification ugly. Ah. Almost.
871
872 If no variable with varName is found anywhere in the stack, this
873 raises a ValueError.
874 """
875 # frame operations are essentially impossible to get through mypy right now.
876 frame = inspect.currentframe().f_back.f_back # type: ignore
877 while frame:
878 if varName in frame.f_locals: # type: ignore
879 return frame.f_locals[varName] # type: ignore
880 frame = frame.f_back # type: ignore
881 raise ValueError("No local %s in the stack"%varName)
882
883
884 def printFrames() -> None: # types: ignore
885 """prints a compact list of frames.
886
887 This is an aid for printf debugging.
888 """
889 frame = inspect.currentframe().f_back.f_back #type: ignore
890 if inspect.getframeinfo(frame)[2]=="getJobsTable": # type: ignore
891 return
892 while frame:
893 print("[%s,%s], [%s]"%inspect.getframeinfo(frame)[:3])
894 frame = frame.f_back
895
896
897 def getTracebackAsString() -> str:
898 import traceback
899 f = io.StringIO()
900 traceback.print_exc(file=f)
901 return f.getvalue()
902
903
904 class EqualingRE(object):
905 """A value that compares equal based on RE matches.
906
907 This is a helper mainly for GetHasXPathsTests. Use an instance of
908 this class to check against an RE rather than a plain string.
909
910 >>> EqualingRE("(ab)+") == "ababab"
911 True
912 >>> EqualingRE("(ab)+$") == "ababa"
913 False
914 >>> EqualingRE("(ab)+$") != "ababa$"
915 True
916 >>> "ababa" == EqualingRE("(ab)+$")
917 False
918 """
919 def __init__(self, pattern: str):
920 self.pat = re.compile(pattern)
921
922 def __eq__(self, other: Any) -> bool:
923 if isinstance(other, str):
924 return bool(self.pat.match(other))
925 elif isinstance(other, EqualingRE):
926 return id(self)==id(other)
927 return False
928
929 def __hash__(self):
930 return hash(self.pat)
931
932 def __ne__(self, other: Any) -> bool:
933 return not self.__eq__(other)
934
935 def __str__(self):
936 return "<Pattern %s>"%self.pat.pattern
937
938 __repr__ = __str__
939
940
941 class NocaseString(str):
942 """A string that compares case-insensitively.
943
944 This is my way to work around the crazy requirement that all kinds of
945 VO protocol parameters need to be case-insensitive. This won't work
946 with dictionaries. It will work with cgi.FieldStorage, though, because
947 it does a linear search.
948
949 Normal DaCHS code doesn't need this because of various hacks in
950 contextgrammar and elsewhere. If you're touching request.args manually,
951 you'll have to look at this, though.
952
953 Case insensitivity is evil. Let's get rid of it and then get rid of
954 this nasty mess.
955 >>> NocaseString("aBc")=="abc"
956 True
957 >>> "aBc"==NocaseString("abc")
958 True
959 >>> NocaseString("axc")=="abc"
960 False
961 >>> NocaseString("axc")!="abc"
962 True
963 >>> NocaseString("axc")!=NocaseString("abc")
964 True
965 """
966 def __eq__(self, other: object):
967 if not hasattr(other, "lower"):
968 return False
969 return self.lower()==other.lower() # type: ignore
970
971
972 # we define different list classes depending to help the sqlsupport
973 # add appropriate casts to NULL (SqlArrayAdapter)
974 class bytelist(list): pass
975 class intlist(list): pass
976 class floatlist(list): pass
977 class complexlist(list): pass
978
979
980 class NS(object):
981 """An object that has its kwargs as attributes.
982 """
983 def __init__(self, **kwargs):
984 for k,v in kwargs.items():
985 setattr(self, k, v)
986
987
988 if __name__=="__main__": # pragma: no cover
989 import doctest
990 doctest.testmod()