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