micropython

lib/builtins.py

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