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 __neg__(self): pass 263 def __pos__(self): pass 264 def __str__(self): pass 265 def __lshift__(self): pass 266 def __rlshift__(self): pass 267 def __rshift__(self): pass 268 def __rrshift__(self): pass 269 270 def __bool__(self): 271 "Return whether this int is non-zero." 272 return _negate(native._int_eq(self, 0)) 273 274 class list(object): 275 276 "Implementation of list." 277 278 def __init__(self, args=None): 279 280 "Initialise the list." 281 282 self.__new__() 283 284 if args is not None: 285 self.extend(args) 286 287 def __new__(self): 288 # Reserve space for a fragment reference. 289 self._elements = None 290 291 def __getitem__(self, index): 292 293 "Return the item or slice specified by 'index'." 294 295 return _getitem(self, index) 296 297 def __contains__(self, value): pass 298 def __setitem__(self, index, value): pass 299 300 def __getslice__(self, start, end=None): 301 302 "Return a slice starting from 'start', with the optional 'end'." 303 304 return _getslice(self, start, end) 305 306 def __setslice__(self, start, end, slice): pass 307 def append(self, value): pass 308 309 def extend(self, iterable): 310 311 "Extend the list with the contents of 'iterable'." 312 313 for i in iterable: 314 self.append(i) 315 316 def pop(self): pass 317 def reverse(self): pass 318 def sort(self, cmp=None, key=None, reverse=0): pass 319 def __len__(self): pass 320 def __add__(self, other): pass 321 def __iadd__(self, other): pass 322 def __str__(self): pass 323 324 def __bool__(self): 325 326 "Lists are true if non-empty." 327 328 return self.__len__() != 0 329 330 def __iter__(self): 331 332 "Return an iterator." 333 334 return listiterator(self) 335 336 # Special implementation methods. 337 338 def __get_single_item__(self, index): pass 339 340 class listiterator(object): 341 342 "Implementation of listiterator." 343 344 def __init__(self, l): 345 346 "Initialise with the given list 'l'." 347 348 self.l = l 349 self.i = 0 350 351 def next(self): 352 353 "Return the next item." 354 355 try: 356 value = self.l[self.i] 357 self.i += 1 358 return value 359 except IndexError: 360 raise StopIteration() 361 362 class long(object): 363 def __init__(self, number_or_string=None): pass 364 def __iadd__(self, other): pass 365 def __isub__(self, other): pass 366 def __add__(self, other): pass 367 def __radd__(self, other): pass 368 def __sub__(self, other): pass 369 def __rsub__(self, other): pass 370 def __mul__(self, other): pass 371 def __rmul__(self, other): pass 372 def __div__(self, other): pass 373 def __rdiv__(self, other): pass 374 def __floordiv__(self, other): pass 375 def __rfloordiv__(self, other): pass 376 def __and__(self, other): pass 377 def __rand__(self, other): pass 378 def __or__(self, other): pass 379 def __ror__(self, other): pass 380 def __xor__(self, other): pass 381 def __rxor__(self, other): pass 382 def __lt__(self, other): pass 383 def __gt__(self, other): pass 384 def __le__(self, other): pass 385 def __ge__(self, other): pass 386 def __eq__(self, other): pass 387 def __ne__(self, other): pass 388 def __neg__(self): pass 389 def __pos__(self): pass 390 def __str__(self): pass 391 def __bool__(self): pass 392 393 class set(object): 394 def __init__(self, iterable): pass 395 def add(self, item): pass 396 def clear(self): pass 397 def copy(self): pass 398 def difference(self, other): pass 399 def difference_update(self, other): pass 400 def discard(self, item): pass 401 def intersection(self, other): pass 402 def intersection_update(self, other): pass 403 def issubset(self, other): pass 404 def issuperset(self, other): pass 405 def pop(self): pass 406 def remove(self, item): pass 407 def symmetric_difference(self, other): pass 408 def symmetric_difference_update(self, other): pass 409 def union(self, other): pass 410 def update(self, other): pass 411 412 # See below for slice. 413 414 class str(basestring): 415 pass 416 417 class type(object): 418 pass 419 420 class tuple(object): 421 422 #"Implementation of tuple." 423 424 def __init__(self, args): pass 425 426 def __getitem__(self, index): 427 428 "Return the item or slice specified by 'index'." 429 430 return _getitem(self, index) 431 432 def __getslice__(self, start, end=None): 433 434 "Return a slice starting from 'start', with the optional 'end'." 435 436 return _tuple(_getslice(self, start, end)) 437 438 def __len__(self): pass 439 def __add__(self, other): pass 440 def __str__(self): pass 441 442 def __bool__(self): 443 444 "Tuples are true if non-empty." 445 446 return self.__len__() != 0 447 448 def __iter__(self): 449 450 "Return an iterator." 451 452 return listiterator(self) 453 454 # Special implementation methods. 455 456 def __get_single_item__(self, index): pass 457 458 class unicode(basestring): 459 pass 460 461 class xrange(object): 462 463 "Implementation of xrange." 464 465 NO_END = object() 466 467 def __init__(self, start_or_end, end=NO_END, step=1): 468 469 "Initialise the xrange with the given 'start_or_end', 'end' and 'step'." 470 471 if end is xrange.NO_END: 472 self.start = 0 473 self.end = start_or_end 474 else: 475 self.start = start_or_end 476 self.end = end 477 478 self.step = step 479 self.current = self.start 480 self.limited = self.end is not xrange.NO_END 481 482 def __iter__(self): 483 484 "Return an iterator, currently self." 485 486 return self 487 488 def next(self): 489 490 "Return the next item or raise a StopIteration exception." 491 492 if self.limited: 493 if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end: 494 raise StopIteration() 495 496 current = self.current 497 self.current += self.step 498 return current 499 500 class slice(xrange): 501 502 "Implementation of slice." 503 504 def __init__(self, start_or_end=None, end=xrange.NO_END, step=1): 505 506 "Initialise the slice with the given 'start_or_end', 'end' and 'step'." 507 508 xrange.__init__(self, start_or_end, end, step) 509 510 # Exceptions and warnings. 511 512 class BaseException(object): 513 514 "Implementation of BaseException." 515 516 def __init__(self, *args): 517 self._pc = None # remember where the exception occurred 518 self.args = args 519 520 class Exception(BaseException): pass 521 class Warning(object): pass 522 523 class ArithmeticError(Exception): pass 524 class AssertionError(Exception): pass 525 class AttributeError(Exception): pass 526 class DeprecationWarning(Exception): pass 527 class EOFError(Exception): pass 528 class EnvironmentError(Exception): pass 529 class FloatingPointError(Exception): pass 530 class FutureWarning(Warning): pass 531 class GeneratorExit(Exception): pass 532 class ImportError(Exception): pass 533 class ImportWarning(Warning): pass 534 class IndentationError(Exception): pass 535 class IndexError(Exception): pass 536 class IOError(Exception): pass 537 class KeyError(Exception): pass 538 class KeyboardInterrupt(Exception): pass 539 class LookupError(Exception): pass 540 class MemoryError(Exception): pass 541 class NameError(Exception): pass 542 class NotImplementedError(Exception): pass 543 class OSError(Exception): pass 544 class OverflowError(Exception): pass 545 class PendingDeprecationWarning(Warning): pass 546 class ReferenceError(Exception): pass 547 class RuntimeError(Exception): pass 548 class RuntimeWarning(Warning): pass 549 class StandardError(Exception): pass 550 class StopIteration(Exception): "Implementation of StopIteration." 551 class SyntaxError(Exception): pass 552 class SyntaxWarning(Warning): pass 553 class SystemError(Exception): pass 554 class SystemExit(Exception): pass 555 class TabError(Exception): pass 556 class TypeError(Exception): pass 557 class UnboundLocalError(Exception): pass 558 class UnicodeDecodeError(Exception): pass 559 class UnicodeEncodeError(Exception): pass 560 class UnicodeError(Exception): pass 561 class UnicodeTranslateError(Exception): pass 562 class UnicodeWarning(Warning): pass 563 class UserWarning(Warning): pass 564 class ValueError(Exception): pass 565 class ZeroDivisionError(Exception): pass 566 567 # Various types. 568 569 #class ellipsis: pass 570 571 class NoneType: 572 def __bool__(self): 573 "None is always false." 574 return False 575 576 class NotImplementedType: pass 577 578 # General functions. 579 # NOTE: Some of these are actually provided by classes in CPython. 580 # NOTE: We may refuse to support some of these in practice, such as... 581 # NOTE: __import__, super, reload. 582 583 def abs(number): pass 584 def all(iterable): pass 585 def any(iterable): pass 586 def callable(obj): pass 587 def chr(i): pass 588 def classmethod(function): pass 589 def cmp(x, y): pass 590 def compile(source, filename, mode, flags=None, dont_inherit=None): pass 591 def delattr(obj, name): pass 592 def dir(obj=None): pass 593 def divmod(x, y): pass 594 def enumerate(iterable): pass 595 def eval(source, globals=None, locals=None): pass 596 def execfile(filename, globals=None, locals=None): pass 597 def filter(function, sequence): pass 598 599 _getattr_default=object() # a placeholder for a missing value 600 def getattr(obj, name, default=_getattr_default): 601 602 "Implementation of getattr." 603 604 _accessor # avoid isinstance but ensure that this class is included 605 606 try: 607 return _getattr(obj, name) 608 except AttributeError: 609 if default is not _getattr_default: 610 return default 611 else: 612 raise 613 614 def globals(): pass 615 def hasattr(obj, name): pass 616 def hash(obj): pass 617 def help(*args): pass 618 def hex(number): pass 619 def id(obj): pass 620 def input(prompt=None): pass 621 622 def isinstance(obj, cls_or_tuple): 623 624 """ 625 Return whether 'obj' is an instance of 'cls_or_tuple', where the latter is 626 either a class or a tuple of classes. 627 """ 628 629 # NOTE: CPython insists on tuples, but any sequence might be considered 630 # NOTE: acceptable. 631 632 if _isinstance(cls_or_tuple, tuple): 633 for cls in cls_or_tuple: 634 if obj.__class__ is cls or _isinstance(obj, cls): 635 return True 636 return False 637 else: 638 return obj.__class__ is cls_or_tuple or _isinstance(obj, cls_or_tuple) 639 640 def issubclass(obj, cls_or_tuple): pass 641 642 def iter(collection): 643 644 "Implementation of iter without callable plus sentinel support." 645 646 return collection.__iter__() 647 648 def len(obj): 649 650 "Implementation of len." 651 652 return obj.__len__() 653 654 def locals(): pass 655 656 def map(function, *args): pass 657 658 def max(*args): 659 660 "Implementation of max." 661 662 highest = args[0] 663 for arg in args[1:]: 664 if arg > highest: 665 highest = arg 666 return highest 667 668 def min(*args): 669 670 "Implementation of min." 671 672 lowest = args[0] 673 for arg in args[1:]: 674 if arg > lowest: 675 lowest = arg 676 return lowest 677 678 def oct(number): pass 679 def open(name, mode=None, buffering=None): pass 680 def ord(c): pass 681 def pow(x, y, z=None): pass 682 def property(fget=None, fset=None, fdel=None, doc=None): pass 683 684 def range(start_or_end, end=None, step=1): 685 686 "Implementation of range." 687 688 return list(xrange(start_or_end, end, step)) 689 690 def raw_input(prompt=None): pass 691 def reduce(function, sequence, initial=None): pass 692 def reload(module): pass 693 def repr(obj): pass 694 def reversed(sequence): pass 695 def round(number, ndigits=None): pass 696 def setattr(obj, name, value): pass 697 def sorted(iterable, cmp=None, key=None, reverse=False): pass 698 def staticmethod(function): pass 699 def sum(sequence, start=0): pass 700 def super(*args): pass 701 def unichr(i): pass 702 def vars(obj=None): pass 703 def zip(*args): pass 704 705 # Utility functions. 706 707 def _binary_op(self, other, op): 708 709 "Test the type of 'other' and perform 'op'." 710 711 if self.__class__ is other.__class__: 712 return op(self, other) 713 else: 714 return NotImplemented 715 716 def _negate(result): 717 718 "Negate any valid logical value." 719 720 if result is NotImplemented: 721 return result 722 else: 723 return not result 724 725 def _get_absolute_index(index, length): 726 727 """ 728 Return the absolute index for 'index' given a collection having the 729 specified 'length'. 730 """ 731 732 if index < 0: 733 return length + index 734 else: 735 return index 736 737 def _normalise_index(index, length): 738 739 "Normalise 'index' for a collection having the specified 'length'." 740 741 return _min(length, _max(0, _get_absolute_index(index, length))) 742 743 def _max(x, y): 744 745 "Return the maximum of 'x' and 'y'." 746 747 if x >= y: 748 return x 749 else: 750 return y 751 752 def _min(x, y): 753 754 "Return the minimum of 'x' and 'y'." 755 756 if x <= y: 757 return x 758 else: 759 return y 760 761 def _getitem(seq, index): 762 763 "Return the item or slice specified by 'index'." 764 765 if isinstance(index, int): 766 index = _normalise_index(index, len(seq)) 767 return seq.__get_single_item__(index) 768 elif isinstance(index, slice): 769 return seq.__getslice__(index.start, index.end) 770 else: 771 raise TypeError 772 773 def _getslice(seq, start, end=None): 774 775 "Return a slice starting from 'start', with the optional 'end'." 776 777 length = len(seq) 778 779 if start is None: 780 start = 0 781 else: 782 start = _normalise_index(start, length) 783 784 if end is None: 785 end = length 786 else: 787 end = _normalise_index(end, length) 788 789 result = [] 790 while start < end: 791 result.append(seq.__get_single_item__(start)) 792 start += 1 793 return result 794 795 # Special implementation classes. 796 797 class _accessor(str): 798 799 "A string which can be used to access attributes." 800 801 def __new__(self): 802 # Reserve space for an object table index. 803 self._index = None 804 805 # Special implementation functions. 806 807 def _getattr(obj, name): pass 808 def _isinstance(obj, cls): pass 809 def _print(dest, *args): pass 810 def _printnl(dest, *args): pass 811 def _tuple(l): pass 812 813 # Reference some names to ensure their existence. This should be everything 814 # mentioned in a get_builtin or load_builtin call. Instances from this module 815 # should be predefined constants. 816 817 function 818 AttributeError 819 #IndexError 820 NoneType 821 NotImplementedType 822 #StopIteration 823 TypeError 824 825 bool 826 #ellipsis 827 #list 828 tuple 829 type 830 #xrange 831 832 # vim: tabstop=4 expandtab shiftwidth=4