-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
ipipe.py
2328 lines (1907 loc) · 70 KB
/
ipipe.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
# -*- coding: iso-8859-1 -*-
"""
``ipipe`` provides classes to be used in an interactive Python session. Doing a
``from ipipe import *`` is the preferred way to do this. The name of all
objects imported this way starts with ``i`` to minimize collisions.
``ipipe`` supports "pipeline expressions", which is something resembling Unix
pipes. An example is::
>>> ienv | isort("key.lower()")
This gives a listing of all environment variables sorted by name.
There are three types of objects in a pipeline expression:
* ``Table``s: These objects produce items. Examples are ``ils`` (listing the
current directory, ``ienv`` (listing environment variables), ``ipwd`` (listing
user accounts) and ``igrp`` (listing user groups). A ``Table`` must be the
first object in a pipe expression.
* ``Pipe``s: These objects sit in the middle of a pipe expression. They
transform the input in some way (e.g. filtering or sorting it). Examples are:
``ifilter`` (which filters the input pipe), ``isort`` (which sorts the input
pipe) and ``ieval`` (which evaluates a function or expression for each object
in the input pipe).
* ``Display``s: These objects can be put as the last object in a pipeline
expression. There are responsible for displaying the result of the pipeline
expression. If a pipeline expression doesn't end in a display object a default
display objects will be used. One example is ``ibrowse`` which is a ``curses``
based browser.
Adding support for pipeline expressions to your own objects can be done through
three extensions points (all of them optional):
* An object that will be displayed as a row by a ``Display`` object should
implement the method ``__xattrs__(self, mode)`` method or register an
implementation of the generic function ``xattrs``. For more info see ``xattrs``.
* When an object ``foo`` is displayed by a ``Display`` object, the generic
function ``xrepr`` is used.
* Objects that can be iterated by ``Pipe``s must iterable. For special cases,
where iteration for display is different than the normal iteration a special
implementation can be registered with the generic function ``xiter``. This
makes it possible to use dictionaries and modules in pipeline expressions,
for example::
>>> import sys
>>> sys | ifilter("isinstance(value, int)") | idump
key |value
api_version| 1012
dllhandle | 503316480
hexversion | 33817328
maxint |2147483647
maxunicode | 65535
>>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
...
Note: The expression strings passed to ``ifilter()`` and ``isort()`` can
refer to the object to be filtered or sorted via the variable ``_`` and to any
of the attributes of the object, i.e.::
>>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
does the same as::
>>> sys.modules | ifilter("value is not None") | isort("key.lower()")
In addition to expression strings, it's possible to pass callables (taking
the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``::
>>> sys | ifilter(lambda _:isinstance(_.value, int)) \
... | ieval(lambda _: (_.key, hex(_.value))) | idump
0 |1
api_version|0x3f4
dllhandle |0x1e000000
hexversion |0x20402f0
maxint |0x7fffffff
maxunicode |0xffff
"""
skip_doctest = True # ignore top-level docstring as a doctest.
import sys, os, os.path, stat, glob, new, csv, datetime, types
import itertools, mimetypes, StringIO
try: # Python 2.3 compatibility
import collections
except ImportError:
deque = list
else:
deque = collections.deque
try: # Python 2.3 compatibility
set
except NameError:
import sets
set = sets.Set
try: # Python 2.3 compatibility
sorted
except NameError:
def sorted(iterator, key=None, reverse=False):
items = list(iterator)
if key is not None:
items.sort(lambda i1, i2: cmp(key(i1), key(i2)))
else:
items.sort()
if reverse:
items.reverse()
return items
try: # Python 2.4 compatibility
GeneratorExit
except NameError:
GeneratorExit = SystemExit
try:
import pwd
except ImportError:
pwd = None
try:
import grp
except ImportError:
grp = None
from IPython.external import simplegeneric
from IPython.external import path
try:
import IPython.utils.io
from IPython.utils import generics
except ImportError:
Term = None
generics = None
from IPython.core import ipapi
__all__ = [
"ifile", "ils", "iglob", "iwalk", "ipwdentry", "ipwd", "igrpentry", "igrp",
"icsv", "ix", "ichain", "isort", "ifilter", "ieval", "ienum",
"ienv", "ihist", "ialias", "icap", "idump", "iless"
]
os.stat_float_times(True) # enable microseconds
class AttrNamespace(object):
"""
Helper class that is used for providing a namespace for evaluating
expressions containing attribute names of an object.
"""
def __init__(self, wrapped):
self.wrapped = wrapped
def __getitem__(self, name):
if name == "_":
return self.wrapped
try:
return getattr(self.wrapped, name)
except AttributeError:
raise KeyError(name)
# Python 2.3 compatibility
# use eval workaround to find out which names are used in the
# eval string and put them into the locals. This works for most
# normal uses case, bizarre ones like accessing the locals()
# will fail
try:
eval("_", None, AttrNamespace(None))
except TypeError:
real_eval = eval
def eval(codestring, _globals, _locals):
"""
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mappping.
This function is a workaround for the shortcomings of
Python 2.3's eval.
"""
if isinstance(codestring, basestring):
code = compile(codestring, "_eval", "eval")
else:
code = codestring
newlocals = {}
for name in code.co_names:
try:
newlocals[name] = _locals[name]
except KeyError:
pass
return real_eval(code, _globals, newlocals)
noitem = object()
def item(iterator, index, default=noitem):
"""
Return the ``index``th item from the iterator ``iterator``.
``index`` must be an integer (negative integers are relative to the
end (i.e. the last items produced by the iterator)).
If ``default`` is given, this will be the default value when
the iterator doesn't contain an item at this position. Otherwise an
``IndexError`` will be raised.
Note that using this function will partially or totally exhaust the
iterator.
"""
i = index
if i>=0:
for item in iterator:
if not i:
return item
i -= 1
else:
i = -index
cache = deque()
for item in iterator:
cache.append(item)
if len(cache)>i:
cache.popleft()
if len(cache)==i:
return cache.popleft()
if default is noitem:
raise IndexError(index)
else:
return default
def getglobals(g):
"""
Return the global namespace that is used for expression strings in
``ifilter`` and others. This is ``g`` or (if ``g`` is ``None``) IPython's
user namespace.
"""
if g is None:
if ipapi is not None:
api = ipapi.get()
if api is not None:
return api.user_ns
return globals()
return g
class Descriptor(object):
"""
A ``Descriptor`` object is used for describing the attributes of objects.
"""
def __hash__(self):
return hash(self.__class__) ^ hash(self.key())
def __eq__(self, other):
return self.__class__ is other.__class__ and self.key() == other.key()
def __ne__(self, other):
return self.__class__ is not other.__class__ or self.key() != other.key()
def key(self):
pass
def name(self):
"""
Return the name of this attribute for display by a ``Display`` object
(e.g. as a column title).
"""
key = self.key()
if key is None:
return "_"
return str(key)
def attrtype(self, obj):
"""
Return the type of this attribute (i.e. something like "attribute" or
"method").
"""
def valuetype(self, obj):
"""
Return the type of this attribute value of the object ``obj``.
"""
def value(self, obj):
"""
Return the value of this attribute of the object ``obj``.
"""
def doc(self, obj):
"""
Return the documentation for this attribute.
"""
def shortdoc(self, obj):
"""
Return a short documentation for this attribute (defaulting to the
first line).
"""
doc = self.doc(obj)
if doc is not None:
doc = doc.strip().splitlines()[0].strip()
return doc
def iter(self, obj):
"""
Return an iterator for this attribute of the object ``obj``.
"""
return xiter(self.value(obj))
class SelfDescriptor(Descriptor):
"""
A ``SelfDescriptor`` describes the object itself.
"""
def key(self):
return None
def attrtype(self, obj):
return "self"
def valuetype(self, obj):
return type(obj)
def value(self, obj):
return obj
def __repr__(self):
return "Self"
selfdescriptor = SelfDescriptor() # there's no need for more than one
class AttributeDescriptor(Descriptor):
"""
An ``AttributeDescriptor`` describes a simple attribute of an object.
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
return self._doc
def attrtype(self, obj):
return "attr"
def valuetype(self, obj):
return type(getattr(obj, self._name))
def value(self, obj):
return getattr(obj, self._name)
def __repr__(self):
if self._doc is None:
return "Attribute(%r)" % self._name
else:
return "Attribute(%r, %r)" % (self._name, self._doc)
class IndexDescriptor(Descriptor):
"""
An ``IndexDescriptor`` describes an "attribute" of an object that is fetched
via ``__getitem__``.
"""
__slots__ = ("_index",)
def __init__(self, index):
self._index = index
def key(self):
return self._index
def attrtype(self, obj):
return "item"
def valuetype(self, obj):
return type(obj[self._index])
def value(self, obj):
return obj[self._index]
def __repr__(self):
return "Index(%r)" % self._index
class MethodDescriptor(Descriptor):
"""
A ``MethodDescriptor`` describes a method of an object that can be called
without argument. Note that this method shouldn't change the object.
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
if self._doc is None:
return getattr(obj, self._name).__doc__
return self._doc
def attrtype(self, obj):
return "method"
def valuetype(self, obj):
return type(self.value(obj))
def value(self, obj):
return getattr(obj, self._name)()
def __repr__(self):
if self._doc is None:
return "Method(%r)" % self._name
else:
return "Method(%r, %r)" % (self._name, self._doc)
class IterAttributeDescriptor(Descriptor):
"""
An ``IterAttributeDescriptor`` works like an ``AttributeDescriptor`` but
doesn't return an attribute values (because this value might be e.g. a large
list).
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
return self._doc
def attrtype(self, obj):
return "iter"
def valuetype(self, obj):
return noitem
def value(self, obj):
return noitem
def iter(self, obj):
return xiter(getattr(obj, self._name))
def __repr__(self):
if self._doc is None:
return "IterAttribute(%r)" % self._name
else:
return "IterAttribute(%r, %r)" % (self._name, self._doc)
class IterMethodDescriptor(Descriptor):
"""
An ``IterMethodDescriptor`` works like an ``MethodDescriptor`` but doesn't
return an attribute values (because this value might be e.g. a large list).
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
if self._doc is None:
return getattr(obj, self._name).__doc__
return self._doc
def attrtype(self, obj):
return "itermethod"
def valuetype(self, obj):
return noitem
def value(self, obj):
return noitem
def iter(self, obj):
return xiter(getattr(obj, self._name)())
def __repr__(self):
if self._doc is None:
return "IterMethod(%r)" % self._name
else:
return "IterMethod(%r, %r)" % (self._name, self._doc)
class FunctionDescriptor(Descriptor):
"""
A ``FunctionDescriptor`` turns a function into a descriptor. The function
will be called with the object to get the type and value of the attribute.
"""
__slots__ = ("_function", "_name", "_doc")
def __init__(self, function, name=None, doc=None):
self._function = function
self._name = name
self._doc = doc
def key(self):
return self._function
def name(self):
if self._name is not None:
return self._name
return getattr(self._function, "__xname__", self._function.__name__)
def doc(self, obj):
if self._doc is None:
return self._function.__doc__
return self._doc
def attrtype(self, obj):
return "function"
def valuetype(self, obj):
return type(self._function(obj))
def value(self, obj):
return self._function(obj)
def __repr__(self):
if self._doc is None:
return "Function(%r)" % self._name
else:
return "Function(%r, %r)" % (self._name, self._doc)
class Table(object):
"""
A ``Table`` is an object that produces items (just like a normal Python
iterator/generator does) and can be used as the first object in a pipeline
expression. The displayhook will open the default browser for such an object
(instead of simply printing the ``repr()`` result).
"""
# We want to support ``foo`` and ``foo()`` in pipeline expression:
# So we implement the required operators (``|`` and ``+``) in the metaclass,
# instantiate the class and forward the operator to the instance
class __metaclass__(type):
def __iter__(self):
return iter(self())
def __or__(self, other):
return self() | other
def __add__(self, other):
return self() + other
def __radd__(self, other):
return other + self()
def __getitem__(self, index):
return self()[index]
def __getitem__(self, index):
return item(self, index)
def __contains__(self, item):
for haveitem in self:
if item == haveitem:
return True
return False
def __or__(self, other):
# autoinstantiate right hand side
if isinstance(other, type) and issubclass(other, (Table, Display)):
other = other()
# treat simple strings and functions as ``ieval`` instances
elif not isinstance(other, Display) and not isinstance(other, Table):
other = ieval(other)
# forward operations to the right hand side
return other.__ror__(self)
def __add__(self, other):
# autoinstantiate right hand side
if isinstance(other, type) and issubclass(other, Table):
other = other()
return ichain(self, other)
def __radd__(self, other):
# autoinstantiate left hand side
if isinstance(other, type) and issubclass(other, Table):
other = other()
return ichain(other, self)
class Pipe(Table):
"""
A ``Pipe`` is an object that can be used in a pipeline expression. It
processes the objects it gets from its input ``Table``/``Pipe``. Note that
a ``Pipe`` object can't be used as the first object in a pipeline
expression, as it doesn't produces items itself.
"""
class __metaclass__(Table.__metaclass__):
def __ror__(self, input):
return input | self()
def __ror__(self, input):
# autoinstantiate left hand side
if isinstance(input, type) and issubclass(input, Table):
input = input()
self.input = input
return self
def xrepr(item, mode="default"):
"""
Generic function that adds color output and different display modes to ``repr``.
The result of an ``xrepr`` call is iterable and consists of ``(style, string)``
tuples. The ``style`` in this tuple must be a ``Style`` object from the
``astring`` module. To reconfigure the output the first yielded tuple can be
a ``(aligment, full)`` tuple instead of a ``(style, string)`` tuple.
``alignment`` can be -1 for left aligned, 0 for centered and 1 for right
aligned (the default is left alignment). ``full`` is a boolean that specifies
whether the complete output must be displayed or the ``Display`` object is
allowed to stop output after enough text has been produced (e.g. a syntax
highlighted text line would use ``True``, but for a large data structure
(i.e. a nested list, tuple or dictionary) ``False`` would be used).
The default is full output.
There are four different possible values for ``mode`` depending on where
the ``Display`` object will display ``item``:
``"header"``
``item`` will be displayed in a header line (this is used by ``ibrowse``).
``"footer"``
``item`` will be displayed in a footer line (this is used by ``ibrowse``).
``"cell"``
``item`` will be displayed in a table cell/list.
``"default"``
default mode. If an ``xrepr`` implementation recursively outputs objects,
``"default"`` must be passed in the recursive calls to ``xrepr``.
If no implementation is registered for ``item``, ``xrepr`` will try the
``__xrepr__`` method on ``item``. If ``item`` doesn't have an ``__xrepr__``
method it falls back to ``repr``/``__repr__`` for all modes.
"""
try:
func = item.__xrepr__
except AttributeError:
yield (astyle.style_default, repr(item))
else:
try:
for x in func(mode):
yield x
except (KeyboardInterrupt, SystemExit, GeneratorExit):
raise
except Exception:
yield (astyle.style_default, repr(item))
xrepr = simplegeneric.generic(xrepr)
def xrepr_none(self, mode="default"):
yield (astyle.style_type_none, repr(self))
xrepr.when_object(None)(xrepr_none)
def xrepr_noitem(self, mode="default"):
yield (2, True)
yield (astyle.style_nodata, "<?>")
xrepr.when_object(noitem)(xrepr_noitem)
def xrepr_bool(self, mode="default"):
yield (astyle.style_type_bool, repr(self))
xrepr.when_type(bool)(xrepr_bool)
def xrepr_str(self, mode="default"):
if mode == "cell":
yield (astyle.style_default, repr(self.expandtabs(tab))[1:-1])
else:
yield (astyle.style_default, repr(self))
xrepr.when_type(str)(xrepr_str)
def xrepr_unicode(self, mode="default"):
if mode == "cell":
yield (astyle.style_default, repr(self.expandtabs(tab))[2:-1])
else:
yield (astyle.style_default, repr(self))
xrepr.when_type(unicode)(xrepr_unicode)
def xrepr_number(self, mode="default"):
yield (1, True)
yield (astyle.style_type_number, repr(self))
xrepr.when_type(int)(xrepr_number)
xrepr.when_type(long)(xrepr_number)
xrepr.when_type(float)(xrepr_number)
def xrepr_complex(self, mode="default"):
yield (astyle.style_type_number, repr(self))
xrepr.when_type(complex)(xrepr_number)
def xrepr_datetime(self, mode="default"):
if mode == "cell":
# Don't use strftime() here, as this requires year >= 1900
yield (astyle.style_type_datetime,
"%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
(self.year, self.month, self.day,
self.hour, self.minute, self.second,
self.microsecond),
)
else:
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.datetime)(xrepr_datetime)
def xrepr_date(self, mode="default"):
if mode == "cell":
yield (astyle.style_type_datetime,
"%04d-%02d-%02d" % (self.year, self.month, self.day))
else:
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.date)(xrepr_date)
def xrepr_time(self, mode="default"):
if mode == "cell":
yield (astyle.style_type_datetime,
"%02d:%02d:%02d.%06d" % \
(self.hour, self.minute, self.second, self.microsecond))
else:
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.time)(xrepr_time)
def xrepr_timedelta(self, mode="default"):
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.timedelta)(xrepr_timedelta)
def xrepr_type(self, mode="default"):
if self.__module__ == "__builtin__":
yield (astyle.style_type_type, self.__name__)
else:
yield (astyle.style_type_type, "%s.%s" % (self.__module__, self.__name__))
xrepr.when_type(type)(xrepr_type)
def xrepr_exception(self, mode="default"):
if self.__class__.__module__ == "exceptions":
classname = self.__class__.__name__
else:
classname = "%s.%s" % \
(self.__class__.__module__, self.__class__.__name__)
if mode == "header" or mode == "footer":
yield (astyle.style_error, "%s: %s" % (classname, self))
else:
yield (astyle.style_error, classname)
xrepr.when_type(Exception)(xrepr_exception)
def xrepr_listtuple(self, mode="default"):
if mode == "header" or mode == "footer":
if self.__class__.__module__ == "__builtin__":
classname = self.__class__.__name__
else:
classname = "%s.%s" % \
(self.__class__.__module__,self.__class__.__name__)
yield (astyle.style_default,
"<%s object with %d items at 0x%x>" % \
(classname, len(self), id(self)))
else:
yield (-1, False)
if isinstance(self, list):
yield (astyle.style_default, "[")
end = "]"
else:
yield (astyle.style_default, "(")
end = ")"
for (i, subself) in enumerate(self):
if i:
yield (astyle.style_default, ", ")
for part in xrepr(subself, "default"):
yield part
yield (astyle.style_default, end)
xrepr.when_type(list)(xrepr_listtuple)
xrepr.when_type(tuple)(xrepr_listtuple)
def xrepr_dict(self, mode="default"):
if mode == "header" or mode == "footer":
if self.__class__.__module__ == "__builtin__":
classname = self.__class__.__name__
else:
classname = "%s.%s" % \
(self.__class__.__module__,self.__class__.__name__)
yield (astyle.style_default,
"<%s object with %d items at 0x%x>" % \
(classname, len(self), id(self)))
else:
yield (-1, False)
if isinstance(self, dict):
yield (astyle.style_default, "{")
end = "}"
else:
yield (astyle.style_default, "dictproxy((")
end = "})"
for (i, (key, value)) in enumerate(self.iteritems()):
if i:
yield (astyle.style_default, ", ")
for part in xrepr(key, "default"):
yield part
yield (astyle.style_default, ": ")
for part in xrepr(value, "default"):
yield part
yield (astyle.style_default, end)
xrepr.when_type(dict)(xrepr_dict)
xrepr.when_type(types.DictProxyType)(xrepr_dict)
def upgradexattr(attr):
"""
Convert an attribute descriptor string to a real descriptor object.
If attr already is a descriptor object return it unmodified. A
``SelfDescriptor`` will be returned if ``attr`` is ``None``. ``"foo"``
returns an ``AttributeDescriptor`` for the attribute named ``"foo"``.
``"foo()"`` returns a ``MethodDescriptor`` for the method named ``"foo"``.
``"-foo"`` will return an ``IterAttributeDescriptor`` for the attribute
named ``"foo"`` and ``"-foo()"`` will return an ``IterMethodDescriptor``
for the method named ``"foo"``. Furthermore integers will return the appropriate
``IndexDescriptor`` and callables will return a ``FunctionDescriptor``.
"""
if attr is None:
return selfdescriptor
elif isinstance(attr, Descriptor):
return attr
elif isinstance(attr, basestring):
if attr.endswith("()"):
if attr.startswith("-"):
return IterMethodDescriptor(attr[1:-2])
else:
return MethodDescriptor(attr[:-2])
else:
if attr.startswith("-"):
return IterAttributeDescriptor(attr[1:])
else:
return AttributeDescriptor(attr)
elif isinstance(attr, (int, long)):
return IndexDescriptor(attr)
elif callable(attr):
return FunctionDescriptor(attr)
else:
raise TypeError("can't handle descriptor %r" % attr)
def xattrs(item, mode="default"):
"""
Generic function that returns an iterable of attribute descriptors
to be used for displaying the attributes ob the object ``item`` in display
mode ``mode``.
There are two possible modes:
``"detail"``
The ``Display`` object wants to display a detailed list of the object
attributes.
``"default"``
The ``Display`` object wants to display the object in a list view.
If no implementation is registered for the object ``item`` ``xattrs`` falls
back to trying the ``__xattrs__`` method of the object. If this doesn't
exist either, ``dir(item)`` is used for ``"detail"`` mode and ``(None,)``
for ``"default"`` mode.
The implementation must yield attribute descriptors (see the class
``Descriptor`` for more info). The ``__xattrs__`` method may also return
attribute descriptor strings (and ``None``) which will be converted to real
descriptors by ``upgradexattr()``.
"""
try:
func = item.__xattrs__
except AttributeError:
if mode == "detail":
for attrname in dir(item):
yield AttributeDescriptor(attrname)
else:
yield selfdescriptor
else:
for attr in func(mode):
yield upgradexattr(attr)
xattrs = simplegeneric.generic(xattrs)
def xattrs_complex(self, mode="default"):
if mode == "detail":
return (AttributeDescriptor("real"), AttributeDescriptor("imag"))
return (selfdescriptor,)
xattrs.when_type(complex)(xattrs_complex)
def _isdict(item):
try:
itermeth = item.__class__.__iter__
except (AttributeError, TypeError):
return False
return itermeth is dict.__iter__ or itermeth is types.DictProxyType.__iter__
def _isstr(item):
if not isinstance(item, basestring):
return False
try:
itermeth = item.__class__.__iter__
except AttributeError:
return True
return False # ``__iter__`` has been redefined
def xiter(item):
"""
Generic function that implements iteration for pipeline expression. If no
implementation is registered for ``item`` ``xiter`` falls back to ``iter``.
"""
try:
func = item.__xiter__
except AttributeError:
if _isdict(item):
def items(item):
fields = ("key", "value")
for (key, value) in item.iteritems():
yield Fields(fields, key=key, value=value)
return items(item)
elif isinstance(item, new.module):
def items(item):
fields = ("key", "value")
for key in sorted(item.__dict__):
yield Fields(fields, key=key, value=getattr(item, key))
return items(item)
elif _isstr(item):
if not item:
raise ValueError("can't enter empty string")
lines = item.splitlines()
if len(lines) == 1:
def iterone(item):
yield item
return iterone(item)
else:
return iter(lines)
return iter(item)
else:
return iter(func()) # iter() just to be safe
xiter = simplegeneric.generic(xiter)
class ichain(Pipe):
"""
Chains multiple ``Table``s into one.
"""
def __init__(self, *iters):
self.iters = iters
def __iter__(self):
return itertools.chain(*self.iters)
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
for (i, item) in enumerate(self.iters):
if i:
yield (astyle.style_default, "+")
if isinstance(item, Pipe):
yield (astyle.style_default, "(")
for part in xrepr(item, mode):
yield part