-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplutilities.py
executable file
·1655 lines (1371 loc) · 65 KB
/
replutilities.py
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import print_function
from collections import Counter, OrderedDict
from enum import Enum, unique, _is_dunder as ispyname
from itertools import chain
import sys, os
# Possible names for builtin modules:
BUILTINS = ('__builtins__', '__builtin__', 'builtins', 'builtin')
# Are we debuggin out?
DEBUG = bool(int(os.environ.get('DEBUG', '0'), base=10))
# On non-macOS platforms this may be awry:
ENCODING = sys.getfilesystemencoding().upper() # 'UTF-8'
# N.B. this may or may not be a PY2/PY3 thing:
MAXINT = getattr(sys, 'maxint',
getattr(sys, 'maxsize', (2 ** 64) / 2))
# Determine if our Python is three’d up:
PY3 = sys.version_info.major > 2
# Determine if we’re on PyPy:
PYPY = hasattr(sys, 'pypy_version_info')
# Determine if we’re in TextMate:
TEXTMATE = 'TM_PYTHON' in os.environ
import io, re
import argparse
import array
import contextlib
import decimal
import warnings
class AutoType(object):
""" Simple polyfill for `enum.auto` (which apparently
does not exist in PyPy 2 for some reason)
"""
def __init__(self):
self.count = 0
def __call__(self, increment=1):
out = int(self.count)
self.count += increment
return out
# Try to get `auto` from `enum`, falling back to the polyfill:
try:
from enum import auto
except ImportError:
auto = AutoType()
# Set up some terminal-printing stuff:
if TEXTMATE:
SEPARATOR_WIDTH = 100
else:
from terminalsize import get_terminal_size
SEPARATOR_WIDTH = get_terminal_size(default=(100, 25))[0]
print_separator = lambda: print('-' * SEPARATOR_WIDTH)
if PY3:
unicode = str
long = int
try:
from collections.abc import Mapping, MutableMapping, Hashable as HashableABC
except ImportError:
from collections import Mapping, MutableMapping, Hashable as HashableABC
try:
from importlib.util import cache_from_source
except ImportError:
# As far as I can tell, this is what Python 2.x does:
cache_from_source = lambda pth: pth + 'c'
try:
from functools import lru_cache
except ImportError:
def lru_cache(**keywrds):
""" No-op dummy decorator for lesser Pythons """
def inside(function):
return function
return inside
try:
from pathlib import Path
except ImportError:
try:
from pathlib2 import Path
except ImportError:
Path = None
pytuple = lambda *attrs: tuple('__%s__' % str(atx) for atx in attrs)
def doctrim(docstring):
""" This function is straight outta PEP257 -- q.v. `trim(…)`,
“Handling Docstring Indentation” subsection sub.:
https://www.python.org/dev/peps/pep-0257/#id18
"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = MAXINT
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < MAXINT:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
def determine_name(thing, name=None, try_repr=False):
""" Private module function to find a name for a thing. """
# Shortcut everything if a name was explictly specified:
if name is not None:
return name
# Check for telltale function-object attributes:
code = None
if hasattr(thing, '__code__'): # Python 3.x
code = thing.__code__
elif hasattr(thing, 'func_code'): # Python 2.x
code = thing.func_code
# Use the function’s code object, if found…
if code is not None:
if hasattr(code, 'co_name'):
name = code.co_name
# … Otherwise, try the standard name attributes:
else:
if hasattr(thing, '__qualname__'):
name = thing.__qualname__
elif hasattr(thing, '__name__'):
name = thing.__name__
# We likely have something by now:
if name is not None:
return name
# If asked to try the thing’s repr, return that:
if try_repr:
return repr(thing)
# LAST RESORT: Search the entire id-space
# of objects within imported modules -- it is
# possible (however unlikely) that this’ll ending
# up returning None:
return thingname_search(thing)
# λ = determine_name(lambda: None)
LAMBDA = determine_name(lambda: None)
# UTILITY FUNCTIONS: boolean predicates for class types
ismetaclass = lambda thing: hasattr(thing, '__mro__') and \
len(thing.__mro__) > 1 and \
thing.__mro__[-2] is type
isclass = lambda thing: (thing is object) or (hasattr(thing, '__mro__') and \
thing.__mro__[-1] is object and \
thing.__mro__[-2] is not type)
isclasstype = lambda thing: hasattr(thing, '__mro__') and \
thing.__mro__[-1] is object
# UTILITY FUNCTIONS: hasattr(…) shortcuts:
haspyattr = lambda thing, atx: hasattr(thing, '__%s__' % atx)
anyattrs = lambda thing, *attrs: any(hasattr(thing, atx) for atx in attrs)
allattrs = lambda thing, *attrs: all(hasattr(thing, atx) for atx in attrs)
anypyattrs = lambda thing, *attrs: any(haspyattr(thing, atx) for atx in attrs)
allpyattrs = lambda thing, *attrs: all(haspyattr(thing, atx) for atx in attrs)
# Things with either __iter__(…) OR __getitem__(…) are iterable:
isiterable = lambda thing: anypyattrs(thing, 'iter', 'getitem')
# q.v. `merge_two(…)` implementation sub.
ismergeable = lambda thing: bool(hasattr(thing, 'get') and isiterable(thing))
# UTILITY FUNCTIONS: getattr(…) shortcuts:
always = lambda thing: True
never = lambda thing: False
nuhuh = lambda thing: None
no_op = lambda thing, atx, default=None: atx or default
or_none = lambda thing, atx: getattr(thing, atx, None)
getpyattr = lambda thing, atx, default=None: getattr(thing, '__%s__' % atx, default)
getitem = lambda thing, itx, default=None: getattr(thing, 'get', no_op)(itx, default)
accessor = lambda function, thing, *attrs: ([atx for atx in (function(thing, atx) \
for atx in attrs) \
if atx is not None] or [None]).pop(0)
searcher = lambda function, xatx, *things: ([atx for atx in (function(thing, xatx) \
for thing in things) \
if atx is not None] or [None]).pop(0)
attr = lambda thing, *attrs: accessor(or_none, thing, *attrs)
pyattr = lambda thing, *attrs: accessor(getpyattr, thing, *attrs)
item = lambda thing, *items: accessor(getitem, thing, *items)
attr_search = lambda atx, *things: searcher(or_none, atx, *things)
pyattr_search = lambda atx, *things: searcher(getpyattr, atx, *things)
item_search = lambda itx, *things: searcher(getitem, itx, *things)
# Does a class contain an attribute -- whether it uses `__dict__` or `__slots__`?
thing_has = lambda thing, atx: atx in (pyattr(thing, 'dict', 'slots') or tuple())
class_has = lambda cls, atx: isclasstype(cls) and thing_has(cls, atx)
# Is this a class based on a `__dict__`, or one using `__slots__`?
isslotted = lambda thing: allpyattrs(thing, 'mro', 'slots')
isdictish = lambda thing: allpyattrs(thing, 'mro', 'dict')
isslotdicty = lambda thing: allpyattrs(thing, 'mro', 'slots', 'dict')
clademap = {
'class' : isclass,
'metaclass' : ismetaclass,
'singleton' : lambda thing: (thing is True) or \
(thing is False) or \
(thing is None) or \
(thing is Ellipsis) or \
(thing is NotImplemented),
'number' : lambda thing: isinstance(thing, (int, long, float, complex)),
'set' : lambda thing: isinstance(thing, (set, frozenset)),
'string' : lambda thing: isinstance(thing, (str, unicode)),
'bytes' : lambda thing: isinstance(thing, (bytes, bytearray, memoryview)),
'lambda' : lambda thing: determine_name(thing) == LAMBDA or \
getpyattr(thing, 'lambda_name') == LAMBDA,
'function' : lambda thing: determine_name(thing) != LAMBDA and \
not haspyattr(thing, 'lambda_name') and \
callable(thing) and \
anyattrs(thing, '__code__', 'func_code'),
'sequence' : lambda thing: isinstance(thing, (tuple, list)),
'dictionary' : lambda thing: isinstance(thing, (dict, Mapping, MutableMapping)),
'iterable' : lambda thing: (not isclasstype(thing)) and \
anypyattrs(thing, 'iter', 'getitem'),
'instance' : lambda thing: (not isclasstype(thing)) and \
isclass(type(thing))
}
NoneType = type(None)
EllipsisType = type(Ellipsis)
NotImplementedType = type(NotImplemented)
SINGLETON_TYPES = (bool, NoneType, EllipsisType, NotImplementedType)
def predicates_for_types(*types):
""" For a list of types, return a list of “isinstance” predicates """
predicates = []
for classtype in frozenset(types):
predicates.append(lambda thing: isinstance(thing, classtype))
return tuple(predicates)
@unique
class Clade(Enum):
""" An enumeration class for classifying exported types. """
CLASS = (isclass, never)
METACLASS = (ismetaclass, never)
SINGLETON = (SINGLETON_TYPES, clademap['singleton'], never)
NUMBER = ((int, long, float, complex), clademap['number'], never)
SET = ((set, frozenset), clademap['set'], never)
STRING = ((str, unicode), clademap['string'], never)
BYTES = ((bytes, bytearray, memoryview), clademap['bytes'], never)
LAMBDA = (clademap['lambda'], never)
FUNCTION = (clademap['function'], never)
SEQUENCE = ((tuple, list), clademap['sequence'], never)
DICTIONARY = ((dict, Mapping, MutableMapping), clademap['dictionary'], never)
ITERABLE = (clademap['iterable'], never)
INSTANCE = (clademap['instance'], never)
@classmethod
def of(cls, thing, name_hint=None):
for clade in cls:
for predicate in clade.predicates:
if predicate(thing):
return clade
thing_hinted_name = name_hint or determine_name(thing)
raise ValueError("can’t determine clade for thing: %s" % thing_hinted_name)
@classmethod
def for_string(cls, string):
for clade in cls:
if clade.to_string() == string.lower():
return clade
raise ValueError("for_string(): unknown clade name %s" % string)
@classmethod
def label_for(cls, thing, name_hint=None):
clade = cls.of(thing, name_hint=name_hint)
return repr(clade)
def __init__(self, *predicates):
typelist = tuple()
if type(predicates[0]) is tuple:
# typelist, *predicates = predicates
typelist = predicates[0]
predicates = predicates[1:]
if not all(isclasstype(putative) for putative in typelist):
raise TypeError("non-class-type item in clade definition")
self.predicates = predicates_for_types(*typelist) + tuple(predicates)
def to_string(self):
return str(self.name.lower())
def __str__(self):
return self.to_string()
def __bytes__(self):
return bytes(self.to_string(), encoding=ENCODING)
def __repr__(self):
return "%s.%s" % (pyattr(type(self), 'qualname', 'name'), self.name)
class ExportError(NameError):
pass
class ExportWarning(Warning):
pass
class NoDefault(object):
__slots__ = tuple()
def __new__(cls, *a, **k):
return cls
case_sort = lambda c: c.lower() if c.isupper() else c.upper()
class Exporter(MutableMapping):
""" A class representing a list of things for a module to export. """
__slots__ = pytuple('exports', 'clades')
def __init__(self):
self.__exports__ = {}
self.__clades__ = Counter()
def exports(self):
""" Get a new dictionary instance filled with the exports. """
out = {}
out.update(self.__exports__)
return out
def clade_histogram(self):
""" Return the histogram of clade counts. """
return Counter(self.__clades__)
messages = {
'docstr' : "Can’t set the docstring for thing “%s” of type %s:",
'xclade' : "Can’t determine a clade for thing “%s” of type %s",
'noname' : "Can’t determine a name for lambda: 0x%0x"
}
def classify(self, thing, named):
""" Attempt to classify a thing to a clade.
Returns a member of the Clade enum.
"""
clade = Clade.of(thing, name_hint=named)
if DEBUG:
print("••• \tthing: %s" % str(thing))
print("••• \tnamed: %s" % str(named))
print("••• \tclade: %s" % repr(clade))
print()
return clade
def increment_for_clade(self, thing, named, increment=1):
clade = self.classify(thing, named=named)
self.__clades__[clade] += int(increment)
return clade
def decrement_for_clade(self, thing, named, decrement=-1):
clade = self.classify(thing, named=named)
self.__clades__[clade] += int(decrement)
return clade
def keys(self):
""" Get a key view on the exported items dictionary. """
return self.__exports__.keys()
def values(self):
""" Get a value view on the exported items dictionary. """
return self.__exports__.values()
def get(self, key, default=NoDefault):
if default is NoDefault:
return self.__exports__.get(key)
return self.__exports__.get(key, default)
def pop(self, key, default=NoDefault):
if key in self.__exports__:
self.decrement_for_clade(self[key], named=key)
if default is NoDefault:
return self.__exports__.pop(key)
return self.__exports__.pop(key, default)
def export(self, thing, name=None, doc=None):
""" Add a function -- or any object, really -- to the export list.
Exported items will end up wih their names in the modules’
`__all__` tuple, and will also be named in the list returned
by the modules’ `__dir__()` function.
It looks better if this method is decoupled from its parent
instance, to wit:
exporter = Exporter()
export = exporter.decorator() # q.v. “decorator()” sub.
Use `export` as a decorator to a function definition:
@export
def yo_dogg(i_heard=None):
…
… or manually, to export anything that doesn’t have a name:
yo_dogg = lambda i_heard=None: …
dogg_heard_index = ( ¬ )
export(yo_dogg, name="yo_dogg")
export(dogg_heard_index, name="dogg_heard_index")
"""
# No explict name was passed -- try to determine one:
named = determine_name(thing, name=name)
# Double-check our determined name and item before stowing:
if named is None:
raise ExportError("can’t export an unnamed thing")
if named in self.__exports__:
raise ExportError("can’t re-export name “%s”" % named)
if thing is self.__exports__:
raise ExportError("can’t export the __exports__ dict directly")
if thing is self:
raise ExportError("can’t export an exporter instance directly")
# Attempt to classify the item to a clade:
try:
self.increment_for_clade(thing, named=named)
except ValueError:
# no clade found
typename = determine_name(type(thing))
warnings.warn(type(self).messages['xclade'] % (named, typename),
ExportWarning, stacklevel=2)
# At this point, “named” is valid -- if we were passed
# a lambda, try to rename it with either our valid name,
# or the result of an ID-based search for that lambda:
if callable(thing):
if getattr(thing, '__name__', '') == LAMBDA:
if named == LAMBDA:
named = thingname_search(thing)
if named is None:
raise ExportError(type(self).messages['noname'] % id(thing))
thing.__name__ = thing.__qualname__ = named
thing.__lambda_name__ = LAMBDA # To recall the lambda’s genesis
# If a “doc” argument was passed in, attempt to assign
# the __doc__ attribute accordingly on the item -- note
# that this won’t work for e.g. slotted, builtin, or C-API
# types that lack mutable __dict__ internals (or at least
# a settable __doc__ slot or established attribute).
if doc is not None:
try:
thing.__doc__ = doctrim(doc)
except (AttributeError, TypeError):
typename = determine_name(type(thing))
warnings.warn(type(self).messages['docstr'] % (named, typename),
ExportWarning, stacklevel=2)
# Stow the item in the global __exports__ dict:
self.__exports__[named] = thing
# Return the thing, unchanged (that’s how we decorate).
return thing
def decorator(self):
""" Return a reference to this Exporter instances’ “export”
method, suitable for use as a decorator, e.g.:
export = exporter.decorator()
@export
def yodogg():
''' Yo dogg, I heard you like exporting '''
…
… This should be done near the beginning of a module,
to facilitate marking functions and other objects to be
exported – q.v. the “all_and_dir()” method sub.
"""
return self.export
def __call__(self):
""" Exporter instances are callable, for use in `__all__` definitions """
return tuple(self.keys())
def dir_function(self):
""" Return a list containing the exported module names. """
return list(self.keys())
def all_and_dir(self):
""" Assign a modules’ __all__ and __dir__ values, e.g.:
__all__, __dir__ = exporter.all_and_dir()
… This should be done near the end of a module, after
all calls to `exporter.export(…)` (aka @export) have
been made – q.v. the “decorator()” method supra.
"""
return self(), self.dir_function
def dir_and_all(self):
""" Assign a modules’ __dir__ and __all__ values, e.g.:
__dir__, __all__ = exporter.dir_and_all()
… This should be done near the end of a module, after
all calls to `exporter.export(…)` (aka @export) have
been made – q.v. the “decorator()” method supra.
"""
return self.dir_function, self() # OPPOSITE!
def cache_info(self):
""" Shortcut to get the CacheInfo namedtuple from the
cached internal `thingname_search_by_id(…)` function,
which is used in last-resort name lookups made by
`determine_name(…)` during `export(…)` calls.
"""
return thingname_search_by_id.cache_info()
def _print_export_list(self):
""" Print out a prettified (IMHO at any rate) representation of
the current module export list.
N.B. This function is a fucking illegible mess at the moment
"""
from pprint import pformat
exports = self.exports()
keys = sorted(exports.keys(), key=case_sort, reverse=True)
vals = (getitem(exports, key) for key in keys)
print_separator()
print("≠≠≠ EXPORTS: (length = %i)" % len(keys))
print()
od = OrderedDict.fromkeys(keys)
od.update(zip(keys, vals))
for idx, (key, value) in enumerate(reversed(od.items())):
prelude = "%03d → [ %24s ] →" % (idx, key)
print(prelude, " %s" % re.subn(r'\n', '\n' + " " * (len(prelude) + 2),
pformat(value,
width=SEPARATOR_WIDTH,
compact=True), flags=re.MULTILINE)[0])
def _print_clade_histogram(self):
""" Print out a bar graph of the current clade histogram.
Like e.g. this:
---------------------------------------------------------------------------------
≠≠≠ CLASSIFICATION HISTOGRAM
≠≠≠ Clades: 8 (of 12)
≠≠≠ Things: 102 total, 0 unclassified
00 → [ LAMBDA ] → 46 • 45% ••••••••••••••••••••••••••••••••••••••••••••••
01 → [ FUNCTION ] → 28 • 27% ••••••••••••••••••••••••••••
02 → [ SEQUENCE ] → 10 • 9% ••••••••••
03 → [ CLASS ] → 8 • 7% ••••••••
04 → [ SINGLETON ] → 3 • 2% •••
05 → [ STRING ] → 3 • 2% •••
06 → [ DICTIONARY ] → 2 • 1% ••
07 → [ NUMBER ] → 2 • 1% ••
≠≠≠ 4 leaf clades:
≠≠≠ instance, iterable, metaclass, set
---------------------------------------------------------------------------------
"""
clade_histogram = self.clade_histogram()
total = sum(clade_histogram.values())
unclassified = len(self) - total
print_separator()
print("≠≠≠ CLASSIFICATION HISTOGRAM")
print("≠≠≠ Clades: %i (of %i)" % (len(clade_histogram), len(Clade)))
print("≠≠≠ Things: %i total, %i unclassified" % (total, unclassified))
print()
for idx, (clade, count) in enumerate(sorted(clade_histogram.items(),
key=lambda item: item[1],
reverse=True)):
prelude = "%02d → [ %12s ] → %2i • %s%%" % (idx,
clade.name,
count,
str(int((count / total) * 100)).rjust(2)) # percent
print(prelude, "•" * count) # ASCII histogram bar graph
print()
leafclades = frozenset(Clade) - frozenset(clade_histogram.keys())
if len(leafclades) > 0:
print("≠≠≠ %i leaf clades:" % len(leafclades))
print("≠≠≠ %s" % ", ".join(sorted(clade.to_string() for clade in leafclades)))
print()
def _print_cache_info(self):
""" Print out the “CacheInfo” namedtuple from the search-by-ID
cached thingname function (q.v. “cache_info()” method supra.)
"""
from pprint import pprint
print_separator()
print("≠≠≠ THINGNAME SEARCH-BY-ID CACHE INFO:")
print()
pprint(self.cache_info())
def print_diagnostics(self, module_all, module_dir):
""" Pretty-print the current list of exported things """
# Sanity-check the modules’ __dir__ and __all__ attributes
exports = self.exports()
assert list(module_all) == module_dir()
assert len(module_all) == len(module_dir())
assert len(module_all) == len(exports)
# Pretty-print the export list
self._print_export_list()
# Pretty-print the clade histogram
self._print_clade_histogram()
# Print the cache info
if PY3:
self._print_cache_info()
# Print closing separators
print_separator()
print()
def __iter__(self):
return iter(self.__exports__.keys())
def __len__(self):
return len(self.__exports__)
def __contains__(self, key):
return key in self.__exports__
def __getitem__(self, key):
return self.__exports__[key]
def __setitem__(self, key, value):
if key in self.__exports__:
self.decrement_for_clade(self[key], named=key)
self.increment_for_clade(value, named=key)
self.__exports__[key] = value
def __delitem__(self, key):
self.decrement_for_clade(self[key], named=key)
del self.__exports__[key]
def __bool__(self):
return len(self.__exports__) > 0
exporter = Exporter()
export = exporter.decorator()
# MODULE SEARCH FUNCTIONS: iterate and search modules, yielding
# names, thing values, and/or id(thing) values, matching by given
# by thing names or id(thing) values
@export
def itermodule(module):
""" Get an iterable of `(name, thing)` tuples for all things
contained in a given module (although it’ll probably work
for classes and instances too – anything `dir()`-able.)
"""
keys = tuple(key for key in sorted(dir(module)) \
if key not in BUILTINS)
values = (getattr(module, key) for key in keys)
return zip(keys, values)
@export
def moduleids(module):
""" Get a dictionary of `(name, thing)` tuples from a module,
indexed by the `id()` value of `thing`
"""
out = {}
for key, thing in itermodule(module):
out[id(thing)] = (key, thing)
return out
@export
def thingname(original, *modules):
""" Find the name of a thing, according to what it is called
in the context of a module in which it resides
"""
inquestion = id(original)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for module in frozenset(modules):
for key, thing in itermodule(module):
if id(thing) == inquestion:
return key
return None
def itermoduleids(module):
""" Internal function to get an iterable of `(name, id(thing))`
tuples for all things comntained in a given module – q.v.
`itermodule(…)` implementation supra.
"""
keys = tuple(key for key in dir(module) \
if key not in BUILTINS)
ids = (id(getattr(module, key)) for key in keys)
return zip(keys, ids)
# UTILITY FUNCTIONS: helpers for builtin container types:
@export
def tuplize(*items):
""" Return a new tuple containing all non-`None` arguments """
return tuple(item for item in items if item is not None)
@export
def uniquify(*items):
""" Return a tuple with a unique set of all non-`None` arguments """
return tuple(frozenset(item for item in items if item is not None))
@export
def listify(*items):
""" Return a new list containing all non-`None` arguments """
return list(item for item in items if item is not None)
# Q.v. `thingname_search_by_id(…)` function sub.
cache = lru_cache(maxsize=128, typed=False)
# This goes against all logic and reason, but it fucking seems
# to fix the problem of constants, etc showing up erroneously
# as members of the `__console__` or `__main__` modules –
# a problem which, I should mention, is present in the operation
# of the `pickle.whichmodule(…)` function (!)
sysmods = lambda: reversed(uniquify(*sys.modules.values()))
@cache
def thingname_search_by_id(thingID):
""" Cached function to find the name of a thing, according
to what it is called in the context of a module in which
it resides – searching across all currently imported
modules in entirely, as indicated from the inspection of
`sys.modules.values()` (which is potentially completely
fucking enormous).
This function implements `thingname_search(…)` – q.v.
the calling function code sub., and is also used in the
implementdation of `determine_module(…)`, - also q.v.
the calling function code sub.
Caching courtesy the `functools.lru_cache(…)` decorator.
"""
# Would you believe that the uniquify(…) call is absolutely
# fucking necessary to use on `sys.modules`?! I checked and
# on my system, like on all my REPLs, uniquifying the modules
# winnowed the module list (and therefore, this functions’
# search space) by around 100 fucking modules (!) every time!!
with warnings.catch_warnings():
warnings.simplefilter("ignore")
for module in sysmods():
for key, valueID in itermoduleids(module):
if valueID == thingID:
return module, key
return None, None
@export
def thingname_search(thing):
""" Attempt to find the name for thing, using the logic from
the `thingname(…)` function, applied to all currently
imported modules, as indicated from the inspection of
`sys.modules.values()` (which that, as a search space,
is potentially fucking enormous).
This function may be called by `determine_name(…)`. Its
subordinate internal function, `thingname_search_by_id(…)`,
uses the LRU cache from `functools`.
"""
return thingname_search_by_id(id(thing))[1]
@export
def slots_for(cls):
""" Get the summation of the `__slots__` tuples for a class and its ancestors """
# q.v. https://stackoverflow.com/a/6720815/298171
if not haspyattr(cls, 'mro'):
return tuple()
return tuple(chain.from_iterable(
getpyattr(ancestor, 'slots', tuple()) \
for ancestor in cls.__mro__))
@export
def nameof(thing, fallback=''):
""" Get the name of a thing, according to either:
>>> thing.__qualname__
… or:
>>> thing.__name__
… optionally specifying a fallback string.
"""
return determine_name(thing) or fallback
@export
def determine_module(thing):
""" Determine in which module a given thing is ensconced,
and return that modules’ name as a string.
"""
return pyattr(thing, 'module', 'package') or \
determine_name(
thingname_search_by_id(id(thing))[0])
# UTILITY FUNCTIONS: dictionary-merging
def merge_two(one, two, cls=dict):
""" Merge two dictionaries into an instance of the specified class
Based on this docopt example source: https://git.io/fjCZ6
"""
if not cls:
cls = type(one)
keys = frozenset(one) | frozenset(two)
merged = ((key, one.get(key, None) or two.get(key, None)) for key in keys)
return cls(merged)
@export
def merge_as(*dicts, **overrides):
""" Merge all dictionary arguments into a new instance of the specified class,
passing all additional keyword arguments to the class constructor as overrides
"""
cls = overrides.pop('cls', dict)
if not cls:
cls = len(dicts) and type(dicts[0]) or dict
merged = cls(**overrides)
for d in dicts:
merged = merge_two(merged, d, cls=cls)
return merged
@export
def merge(*dicts, **overrides):
""" Merge all dictionary arguments into a new `dict` instance, using any
keyword arguments as item overrides in the final `dict` instance returned
"""
if 'cls' in overrides:
raise NameError('Cannot override the `cls` value')
return merge_as(*dicts, cls=dict, **overrides)
# UTILITY STUFF: asdict(…)
@export
def asdict(thing):
""" asdict(thing) → returns either thing, thing.__dict__, or dict(thing) as necessary """
if isinstance(thing, dict):
return thing
if haspyattr(thing, 'dict'):
return thing.__dict__
return dict(thing)
# UTILITY STUFF: SimpleNamespace and Namespace
@export
class SimpleNamespace(object):
""" Implementation courtesy this SO answer:
• https://stackoverflow.com/a/37161391/298171
"""
__slots__ = pytuple('dict', 'weakref')
def __init__(self, *args, **kwargs):
for arg in args:
self.__dict__.update(asdict(arg))
self.__dict__.update(kwargs)
def __iter__(self):
return iter(self.__dict__.keys())
def __repr__(self):
items = ("{}={!r}".format(key, self.__dict__[key]) for key in sorted(self))
return "{}({}) @ {}".format(determine_name(type(self)),
",\n".join(items), id(self))
def __eq__(self, other):
return self.__dict__ == asdict(other)
def __ne__(self, other):
return self.__dict__ != asdict(other)
@export
class Namespace(SimpleNamespace, MutableMapping):
""" Namespace adds the `get(…)`, `__len__()`, `__contains__(…)`, `__getitem__(…)`,
`__setitem__(…)`, `__add__(…)`, and `__bool__()` methods to its ancestor class
implementation SimpleNamespace.
Since it implements a `get(…)` method, Namespace instances can be passed
to `merge(…)` – q.v. `merge(…)` function definition supra.
Additionally, Namespace furnishes an `__all__` property implementation.
"""
__slots__ = tuple()
winnower = re.compile(r"\{(?:\s+)(?P<stuff>.+)")
def get(self, key, default=NoDefault):
""" Return the value for key if key is in the dictionary, else default. """
if default is NoDefault:
return self.__dict__.get(key)
return self.__dict__.get(key, default)
@property
def __all__(self):
""" Get a tuple with all the stringified keys in the Namespace. """
return tuple(str(key) for key in sorted(self))
def __repr__(self):
from pprint import pformat
return "{}({}) @ {}".format(determine_name(type(self)),
self.winnower.sub('{\g<stuff>',
pformat(self.__dict__,
width=SEPARATOR_WIDTH)),
id(self))
def __len__(self):
return len(self.__dict__)
def __contains__(self, key):
return key in self.__dict__
def __getitem__(self, key):
return self.__dict__.__getitem__(key)
def __setitem__(self, key, value):
self.__dict__.__setitem__(key, value)
def __delitem__(self, key):
self.__dict__.__delitem__(key)
def __add__(self, operand):
# On add, old values are not overwritten
if not ismergeable(operand):
return NotImplemented
return merge_two(self, operand, cls=type(self))
def __radd__(self, operand):
# On reverse-add, old values are overwritten
if not ismergeable(operand):
return NotImplemented
return merge_two(operand, self, cls=type(self))
def __iadd__(self, operand):
# On in-place add, old values are updated and replaced
if not ismergeable(operand):
return NotImplemented
self.__dict__.update(asdict(operand))
return self
def __or__(self, operand):
return self.__add__(operand)
def __ror__(self, operand):
return self.__radd__(operand)
def __ior__(self, operand):
return self.__iadd__(operand)
def __bool__(self):
return bool(self.__dict__)
VERBOTEN = pytuple('all', 'cached', 'loader', 'file', 'spec')
VERBOTEN += BUILTINS
VERBOTEN += ('Namespace', 'SimpleNamespace')
import types as thetypes
types = Namespace()
typed = re.compile(r"^(?P<typename>\w+)(?:Type)$")
# Fill a Namespace with type aliases, minus the fucking 'Type' suffix --
# We know they are types because they are in the fucking “types” module, OK?
# And those irritating four characters take up too much pointless space, if
# you asked me, which you implicitly did by reading the comments in my code,
# dogg.
for typename in dir(thetypes):
if typename.endswith('Type'):
setattr(types, typed.match(typename).group('typename'),
getattr(thetypes, typename))
elif typename not in VERBOTEN:
setattr(types, typename, getattr(thetypes, typename))
# Substitute our own SimpleNamespace class, instead of the provided version:
setattr(types, 'Namespace', Namespace)
setattr(types, 'SimpleNamespace', SimpleNamespace)