micropython

lib/builtins.py

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