1 #!/usr/bin/env python 2 3 """ 4 Simple built-in classes and functions. 5 6 Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 7 Paul Boddie <paul@boddie.org.uk> 8 9 This program is free software; you can redistribute it and/or modify it under 10 the terms of the GNU General Public License as published by the Free Software 11 Foundation; either version 3 of the License, or (at your option) any later 12 version. 13 14 This program is distributed in the hope that it will be useful, but WITHOUT 15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 16 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 17 details. 18 19 You should have received a copy of the GNU General Public License along with 20 this program. If not, see <http://www.gnu.org/licenses/>. 21 22 -------- 23 24 Objects which provide code that shall always be compiled should provide 25 docstrings. Objects without code should be provided by native library code. 26 27 Classes without docstrings do not have instantiators generated for them. 28 29 Methods defined in classes are generated if they have docstrings, regardless of 30 whether their classes have docstrings. 31 """ 32 33 import native 34 35 class object: 36 def __init__(self): 37 "No-operation." 38 pass 39 def __bool__(self): 40 "Objects are true by default." 41 return True 42 43 class basestring(object): 44 def __init__(self, x=None): pass 45 def __contains__(self, value): pass 46 47 def __getitem__(self, index): 48 # Note usage. 49 IndexError 50 51 def __getslice__(self, start, end=None): pass 52 53 def __iadd__(self, other): 54 "Return a new string for the operation." 55 return _binary_op(self, other, native._str_add) 56 57 __add__ = __radd__ = __iadd__ 58 59 def __mul__(self, other): pass 60 def __rmul__(self, other): pass 61 def __mod__(self, other): pass 62 def __rmod__(self, other): pass 63 64 def __lt__(self, other): 65 "Return a new boolean for the comparison." 66 return _binary_op(self, other, native._str_lt) 67 68 def __gt__(self, other): 69 "Return a new boolean for the comparison." 70 return _binary_op(self, other, native._str_gt) 71 72 def __le__(self, other): 73 "Return a new boolean for the comparison." 74 return _negate(self.__gt__(other)) 75 76 def __ge__(self, other): 77 "Return a new boolean for the comparison." 78 return _negate(self.__lt__(other)) 79 80 def __eq__(self, other): 81 "Return a new boolean for the comparison." 82 return _binary_op(self, other, native._str_eq) 83 84 def __ne__(self, other): 85 "Return a new boolean for the comparison." 86 return _negate(self.__eq__(other)) 87 88 def __len__(self): pass 89 def __str__(self): pass 90 91 def __bool__(self): 92 return _negate(native._str_eq(self, "")) 93 94 def join(self, l): pass 95 def split(self, s): pass 96 def startswith(self, s): pass 97 def endswith(self, s): pass 98 99 def __iter__(self): 100 101 "Return an iterator." 102 103 return listiterator(self) 104 105 class bool(object): 106 def __bool__(self): 107 "Identity operation." 108 return self 109 def __str__(self): pass 110 111 class buffer(object): 112 def __init__(self, size): pass 113 def append(self, s): pass 114 def __str__(self): pass 115 116 class complex(object): 117 def __init__(self, real, imag=None): pass 118 119 class dict(object): 120 def __init__(self, *args): pass 121 def __setitem__(self, key, value): pass 122 def __delitem__(self, key, value): pass 123 124 def __getitem__(self, key): 125 # Note usage. 126 KeyError 127 128 def has_key(self): pass 129 def keys(self): pass 130 def values(self): pass 131 def items(self): pass 132 def get(self, key): pass 133 134 class file(object): 135 def read(self, n=None): pass 136 def write(self, s): pass 137 def close(self): pass 138 139 class float(object): 140 def __init__(self, number_or_string=None): pass 141 def __iadd__(self, other): pass 142 def __isub__(self, other): pass 143 def __add__(self, other): pass 144 def __radd__(self, other): pass 145 def __sub__(self, other): pass 146 def __rsub__(self, other): pass 147 def __mul__(self, other): pass 148 def __rmul__(self, other): pass 149 def __div__(self, other): pass 150 def __rdiv__(self, other): pass 151 def __floordiv__(self, other): pass 152 def __rfloordiv__(self, other): pass 153 def __mod__(self, other): pass 154 def __rmod__(self, other): pass 155 def __pow__(self, other): pass 156 def __rpow__(self, other): pass 157 def __lt__(self, other): pass 158 def __gt__(self, other): pass 159 def __le__(self, other): pass 160 def __ge__(self, other): pass 161 def __eq__(self, other): pass 162 def __ne__(self, other): pass 163 def __neg__(self): pass 164 def __pos__(self): pass 165 def __str__(self): pass 166 def __bool__(self): pass 167 168 class frozenset(object): 169 def __init__(self, iterable): pass 170 171 class function(object): 172 pass 173 174 class int(object): 175 def __init__(self, number_or_string=None): pass 176 177 def __iadd__(self, other): 178 "Return a new int for the operation." 179 return _binary_op(self, other, native._int_add) 180 181 def __isub__(self, other): 182 "Return a new int for the operation." 183 return _binary_op(self, other, native._int_sub) 184 185 def __imul__(self, other): 186 "Return a new int for the operation." 187 return _binary_op(self, other, native._int_mul) 188 189 def __idiv__(self, other): 190 "Return a new int for the operation." 191 return _binary_op(self, other, native._int_div) 192 193 def __imod__(self, other): 194 "Return a new int for the operation." 195 return _binary_op(self, other, native._int_mod) 196 197 def __ipow__(self, other): 198 "Return a new int for the operation." 199 return _binary_op(self, other, native._int_pow) 200 201 def __iand__(self, other): 202 "Return a new int for the operation." 203 return _binary_op(self, other, native._int_and) 204 205 def __ior__(self, other): 206 "Return a new int for the operation." 207 return _binary_op(self, other, native._int_or) 208 209 def __ixor__(self, other): 210 "Return a new int for the operation." 211 return _binary_op(self, other, native._int_xor) 212 213 __add__ = __radd__ = __iadd__ 214 __sub__ = __isub__ 215 216 def __rsub__(self, other): 217 "Return a new int for the operation." 218 return _binary_op(self, other, native._int_rsub) 219 220 __mul__ = __rmul__ = __imul__ 221 __div__ = __idiv__ 222 223 def __rdiv__(self, other): 224 "Return a new int for the operation." 225 return _binary_op(self, other, native._int_rdiv) 226 227 def __floordiv__(self, other): pass 228 def __rfloordiv__(self, other): pass 229 230 __mod__ = __imod__ 231 232 def __rmod__(self, other): 233 "Return a new int for the operation." 234 return _binary_op(self, other, native._int_rmod) 235 236 __pow__ = __ipow__ 237 238 def __rpow__(self, other): 239 "Return a new int for the operation." 240 return _binary_op(self, other, native._int_rpow) 241 242 __and__ = __rand__ = __iand__ 243 __or__ = __ror__ = __ior__ 244 __xor__ = __rxor__ = __ixor__ 245 246 def __lt__(self, other): 247 "Return a new boolean for the comparison." 248 return _binary_op(self, other, native._int_lt) 249 250 def __gt__(self, other): 251 "Return a new boolean for the comparison." 252 return _binary_op(self, other, native._int_gt) 253 254 def __le__(self, other): 255 "Return a new boolean for the comparison." 256 return _negate(self.__gt__(other)) 257 258 def __ge__(self, other): 259 "Return a new boolean for the comparison." 260 return _negate(self.__lt__(other)) 261 262 def __eq__(self, other): 263 "Return a new boolean for the comparison." 264 return _binary_op(self, other, native._int_eq) 265 266 def __ne__(self, other): 267 "Return a new boolean for the comparison." 268 return _negate(self.__eq__(other)) 269 270 def __invert__(self): pass 271 def __neg__(self): pass 272 def __pos__(self): pass 273 def __str__(self): pass 274 def __lshift__(self): pass 275 def __rlshift__(self): pass 276 def __rshift__(self): pass 277 def __rrshift__(self): pass 278 279 def __bool__(self): 280 "Return whether this int is non-zero." 281 return _negate(native._int_eq(self, 0)) 282 283 class list(object): 284 285 "Implementation of list." 286 287 def __init__(self, args=None): 288 289 "Initialise the list." 290 291 self.__new__() 292 293 if args is not None: 294 self.extend(args) 295 296 def __new__(self): 297 # Reserve space for a fragment reference. 298 self._elements = None 299 300 def __getitem__(self, index): 301 302 "Return the item or slice specified by 'index'." 303 304 return _getitem(self, index) 305 306 def __contains__(self, value): pass 307 def __setitem__(self, index, value): pass 308 def __delitem__(self, index): pass 309 310 def __getslice__(self, start, end=None): 311 312 "Return a slice starting from 'start', with the optional 'end'." 313 314 return _getslice(self, start, end) 315 316 def __setslice__(self, start, end, slice): pass 317 def __delslice__(self, start, end): pass 318 def append(self, value): pass 319 320 def extend(self, iterable): 321 322 "Extend the list with the contents of 'iterable'." 323 324 for i in iterable: 325 self.append(i) 326 327 def pop(self): pass 328 def reverse(self): pass 329 def sort(self, cmp=None, key=None, reverse=0): pass 330 def __len__(self): pass 331 def __add__(self, other): pass 332 def __iadd__(self, other): pass 333 def __str__(self): pass 334 335 def __bool__(self): 336 337 "Lists are true if non-empty." 338 339 return self.__len__() != 0 340 341 def __iter__(self): 342 343 "Return an iterator." 344 345 return listiterator(self) 346 347 # Special implementation methods. 348 349 def __get_single_item__(self, index): pass 350 351 class listiterator(object): 352 353 "Implementation of listiterator." 354 355 def __init__(self, l): 356 357 "Initialise with the given list 'l'." 358 359 self.l = l 360 self.i = 0 361 362 def next(self): 363 364 "Return the next item." 365 366 try: 367 value = self.l[self.i] 368 self.i += 1 369 return value 370 except IndexError: 371 raise StopIteration() 372 373 class long(object): 374 def __init__(self, number_or_string=None): pass 375 def __iadd__(self, other): pass 376 def __isub__(self, other): pass 377 def __add__(self, other): pass 378 def __radd__(self, other): pass 379 def __sub__(self, other): pass 380 def __rsub__(self, other): pass 381 def __mul__(self, other): pass 382 def __rmul__(self, other): pass 383 def __div__(self, other): pass 384 def __rdiv__(self, other): pass 385 def __floordiv__(self, other): pass 386 def __rfloordiv__(self, other): pass 387 def __and__(self, other): pass 388 def __rand__(self, other): pass 389 def __or__(self, other): pass 390 def __ror__(self, other): pass 391 def __xor__(self, other): pass 392 def __rxor__(self, other): pass 393 def __lt__(self, other): pass 394 def __gt__(self, other): pass 395 def __le__(self, other): pass 396 def __ge__(self, other): pass 397 def __eq__(self, other): pass 398 def __ne__(self, other): pass 399 def __neg__(self): pass 400 def __pos__(self): pass 401 def __str__(self): pass 402 def __bool__(self): pass 403 404 class property(object): 405 def __init__(fget=None, fset=None, fdel=None, doc=None): pass 406 407 class set(object): 408 def __init__(self, iterable): pass 409 def add(self, item): pass 410 def clear(self): pass 411 def copy(self): pass 412 def difference(self, other): pass 413 def difference_update(self, other): pass 414 def discard(self, item): pass 415 def intersection(self, other): pass 416 def intersection_update(self, other): pass 417 def issubset(self, other): pass 418 def issuperset(self, other): pass 419 def pop(self): pass 420 def remove(self, item): pass 421 def symmetric_difference(self, other): pass 422 def symmetric_difference_update(self, other): pass 423 def union(self, other): pass 424 def update(self, other): pass 425 426 # See below for slice. 427 428 class str(basestring): 429 pass 430 431 class type(object): 432 pass 433 434 class tuple(object): 435 436 #"Implementation of tuple." 437 438 def __init__(self, args): pass 439 440 def __getitem__(self, index): 441 442 "Return the item or slice specified by 'index'." 443 444 return _getitem(self, index) 445 446 def __getslice__(self, start, end=None): 447 448 "Return a slice starting from 'start', with the optional 'end'." 449 450 return _tuple(_getslice(self, start, end)) 451 452 def __len__(self): pass 453 def __add__(self, other): pass 454 def __str__(self): pass 455 456 def __bool__(self): 457 458 "Tuples are true if non-empty." 459 460 return self.__len__() != 0 461 462 def __iter__(self): 463 464 "Return an iterator." 465 466 return listiterator(self) 467 468 # Special implementation methods. 469 470 def __get_single_item__(self, index): pass 471 472 class unicode(basestring): 473 pass 474 475 class xrange(object): 476 477 "Implementation of xrange." 478 479 NO_END = object() 480 481 def __init__(self, start_or_end, end=NO_END, step=1): 482 483 "Initialise the xrange with the given 'start_or_end', 'end' and 'step'." 484 485 if end is xrange.NO_END: 486 self.start = 0 487 self.end = start_or_end 488 else: 489 self.start = start_or_end 490 self.end = end 491 492 self.step = step 493 self.current = self.start 494 self.limited = self.end is not xrange.NO_END 495 496 def __iter__(self): 497 498 "Return an iterator, currently self." 499 500 return self 501 502 def next(self): 503 504 "Return the next item or raise a StopIteration exception." 505 506 if self.limited: 507 if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end: 508 raise StopIteration() 509 510 current = self.current 511 self.current += self.step 512 return current 513 514 class slice(xrange): 515 516 "Implementation of slice." 517 518 def __init__(self, start_or_end=None, end=xrange.NO_END, step=1): 519 520 "Initialise the slice with the given 'start_or_end', 'end' and 'step'." 521 522 xrange.__init__(self, start_or_end, end, step) 523 524 # Exceptions and warnings. 525 526 class BaseException(object): 527 528 "Implementation of BaseException." 529 530 def __init__(self, *args): 531 self._pc = None # remember where the exception occurred 532 self.args = args 533 534 class Exception(BaseException): pass 535 class Warning(object): pass 536 537 class ArithmeticError(Exception): pass 538 class AssertionError(Exception): pass 539 class AttributeError(Exception): pass 540 class DeprecationWarning(Exception): pass 541 class EOFError(Exception): pass 542 class EnvironmentError(Exception): pass 543 class FloatingPointError(Exception): pass 544 class FutureWarning(Warning): pass 545 class GeneratorExit(Exception): pass 546 class ImportError(Exception): pass 547 class ImportWarning(Warning): pass 548 class IndentationError(Exception): pass 549 class IndexError(Exception): pass 550 class IOError(Exception): pass 551 class KeyError(Exception): pass 552 class KeyboardInterrupt(Exception): pass 553 class LookupError(Exception): pass 554 class MemoryError(Exception): pass 555 class NameError(Exception): pass 556 class NotImplementedError(Exception): pass 557 class OSError(Exception): pass 558 class OverflowError(Exception): pass 559 class PendingDeprecationWarning(Warning): pass 560 class ReferenceError(Exception): pass 561 class RuntimeError(Exception): pass 562 class RuntimeWarning(Warning): pass 563 class StandardError(Exception): pass 564 class StopIteration(Exception): "Implementation of StopIteration." 565 class SyntaxError(Exception): pass 566 class SyntaxWarning(Warning): pass 567 class SystemError(Exception): pass 568 class SystemExit(Exception): pass 569 class TabError(Exception): pass 570 class TypeError(Exception): pass 571 class UnboundLocalError(Exception): pass 572 class UnicodeDecodeError(Exception): pass 573 class UnicodeEncodeError(Exception): pass 574 class UnicodeError(Exception): pass 575 class UnicodeTranslateError(Exception): pass 576 class UnicodeWarning(Warning): pass 577 class UserWarning(Warning): pass 578 class ValueError(Exception): pass 579 class ZeroDivisionError(Exception): pass 580 581 # Various types. 582 583 #class ellipsis: pass 584 585 class NoneType: 586 def __bool__(self): 587 "None is always false." 588 return False 589 590 class NotImplementedType: pass 591 592 # General functions. 593 # NOTE: Some of these are actually provided by classes in CPython. 594 # NOTE: We may refuse to support some of these in practice, such as... 595 # NOTE: __import__, super, reload. 596 597 def abs(number): pass 598 def all(iterable): pass 599 def any(iterable): pass 600 def callable(obj): pass 601 def chr(i): pass 602 def classmethod(function): pass 603 def cmp(x, y): pass 604 def compile(source, filename, mode, flags=None, dont_inherit=None): pass 605 def delattr(obj, name): pass 606 def dir(obj=None): pass 607 def divmod(x, y): pass 608 def enumerate(iterable): pass 609 def eval(source, globals=None, locals=None): pass 610 def execfile(filename, globals=None, locals=None): pass 611 def filter(function, sequence): pass 612 613 _getattr_default=object() # a unique placeholder for a missing value 614 def getattr(obj, name, default=_getattr_default): 615 616 "Implementation of getattr (activating the _accessor type)." 617 618 _accessor # avoid isinstance but ensure that this class is included 619 620 try: 621 return _getattr(obj, name) 622 except AttributeError: 623 if default is not _getattr_default: 624 return default 625 else: 626 raise 627 628 def globals(): pass 629 def hasattr(obj, name): pass 630 def hash(obj): pass 631 def help(*args): pass 632 def hex(number): pass 633 def id(obj): pass 634 def input(prompt=None): pass 635 636 def isinstance(obj, cls_or_tuple): 637 638 """ 639 Return whether 'obj' is an instance of 'cls_or_tuple', where the latter is 640 either a class or a tuple of classes. 641 """ 642 643 # NOTE: CPython insists on tuples, but any sequence might be considered 644 # NOTE: acceptable. 645 646 if _isinstance(cls_or_tuple, tuple): 647 for cls in cls_or_tuple: 648 if obj.__class__ is cls or _isinstance(obj, cls): 649 return True 650 return False 651 else: 652 return obj.__class__ is cls_or_tuple or _isinstance(obj, cls_or_tuple) 653 654 def issubclass(obj, cls_or_tuple): pass 655 656 def iter(collection): 657 658 "Implementation of iter without callable plus sentinel support." 659 660 return collection.__iter__() 661 662 def len(obj): 663 664 "Implementation of len." 665 666 return obj.__len__() 667 668 def locals(): pass 669 670 def map(function, *args): pass 671 672 def max(*args): 673 674 "Implementation of max." 675 676 highest = args[0] 677 for arg in args[1:]: 678 if arg > highest: 679 highest = arg 680 return highest 681 682 def min(*args): 683 684 "Implementation of min." 685 686 lowest = args[0] 687 for arg in args[1:]: 688 if arg > lowest: 689 lowest = arg 690 return lowest 691 692 def oct(number): pass 693 def open(name, mode=None, buffering=None): pass 694 def ord(c): pass 695 def pow(x, y, z=None): pass 696 697 def range(start_or_end, end=None, step=1): 698 699 "Implementation of range." 700 701 return list(xrange(start_or_end, end, step)) 702 703 def raw_input(prompt=None): pass 704 def reduce(function, sequence, initial=None): pass 705 def reload(module): pass 706 def repr(obj): pass 707 def reversed(sequence): pass 708 def round(number, ndigits=None): pass 709 def setattr(obj, name, value): pass 710 def sorted(iterable, cmp=None, key=None, reverse=False): pass 711 def staticmethod(function): pass 712 def sum(sequence, start=0): pass 713 def super(*args): pass 714 def unichr(i): pass 715 def vars(obj=None): pass 716 def zip(*args): pass 717 718 # Utility functions. 719 720 def _binary_op(self, other, op): 721 722 "Test the type of 'other' and perform 'op'." 723 724 if self.__class__ is other.__class__: 725 return op(self, other) 726 else: 727 return NotImplemented 728 729 def _negate(result): 730 731 "Negate any valid logical value." 732 733 if result is NotImplemented: 734 return result 735 else: 736 return not result 737 738 def _get_absolute_index(index, length): 739 740 """ 741 Return the absolute index for 'index' given a collection having the 742 specified 'length'. 743 """ 744 745 if index < 0: 746 return length + index 747 else: 748 return index 749 750 def _normalise_index(index, length): 751 752 "Normalise 'index' for a collection having the specified 'length'." 753 754 return _min(length, _max(0, _get_absolute_index(index, length))) 755 756 def _max(x, y): 757 758 "Return the maximum of 'x' and 'y'." 759 760 if x >= y: 761 return x 762 else: 763 return y 764 765 def _min(x, y): 766 767 "Return the minimum of 'x' and 'y'." 768 769 if x <= y: 770 return x 771 else: 772 return y 773 774 def _getitem(seq, index): 775 776 "Return the item or slice specified by 'index'." 777 778 if isinstance(index, int): 779 index = _normalise_index(index, len(seq)) 780 return seq.__get_single_item__(index) 781 elif isinstance(index, slice): 782 return seq.__getslice__(index.start, index.end) 783 else: 784 raise TypeError 785 786 def _getslice(seq, start, end=None): 787 788 "Return a slice starting from 'start', with the optional 'end'." 789 790 length = len(seq) 791 792 if start is None: 793 start = 0 794 else: 795 start = _normalise_index(start, length) 796 797 if end is None: 798 end = length 799 else: 800 end = _normalise_index(end, length) 801 802 result = [] 803 while start < end: 804 result.append(seq.__get_single_item__(start)) 805 start += 1 806 return result 807 808 # Special implementation classes. 809 810 class _accessor(str): 811 812 "A string which can be used to access attributes." 813 814 def __new__(self): 815 # Reserve space for an object table index. 816 self._index = None 817 818 # Special implementation functions. 819 820 def _getattr(obj, name): pass 821 def _isinstance(obj, cls): pass 822 def _print(dest, *args): pass 823 def _printnl(dest, *args): pass 824 def _tuple(l): pass 825 826 # Reference some names to ensure their existence. This should be everything 827 # mentioned in a get_builtin or load_builtin call. Instances from this module 828 # should be predefined constants. 829 830 function 831 AttributeError 832 #IndexError 833 NoneType 834 NotImplementedType 835 #StopIteration 836 TypeError 837 838 bool 839 #ellipsis 840 #list 841 tuple 842 type 843 #xrange 844 845 # vim: tabstop=4 expandtab shiftwidth=4