Package SCons :: Module Util
[hide private]
[frames] | no frames]

Source Code for Module SCons.Util

   1  """SCons.Util 
   2   
   3  Various utility functions go here. 
   4   
   5  """ 
   6   
   7  # 
   8  # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation 
   9  # 
  10  # Permission is hereby granted, free of charge, to any person obtaining 
  11  # a copy of this software and associated documentation files (the 
  12  # "Software"), to deal in the Software without restriction, including 
  13  # without limitation the rights to use, copy, modify, merge, publish, 
  14  # distribute, sublicense, and/or sell copies of the Software, and to 
  15  # permit persons to whom the Software is furnished to do so, subject to 
  16  # the following conditions: 
  17  # 
  18  # The above copyright notice and this permission notice shall be included 
  19  # in all copies or substantial portions of the Software. 
  20  # 
  21  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY 
  22  # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
  23  # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
  24  # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
  25  # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
  26  # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 
  27  # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
  28  # 
  29   
  30  __revision__ = "src/engine/SCons/Util.py 3603 2008/10/10 05:46:45 scons" 
  31   
  32  import copy 
  33  import os 
  34  import os.path 
  35  import re 
  36  import string 
  37  import sys 
  38  import types 
  39   
  40  from UserDict import UserDict 
  41  from UserList import UserList 
  42  from UserString import UserString 
  43   
  44  # Don't "from types import ..." these because we need to get at the 
  45  # types module later to look for UnicodeType. 
  46  DictType        = types.DictType 
  47  InstanceType    = types.InstanceType 
  48  ListType        = types.ListType 
  49  StringType      = types.StringType 
  50  TupleType       = types.TupleType 
  51   
52 -def dictify(keys, values, result={}):
53 for k, v in zip(keys, values): 54 result[k] = v 55 return result
56 57 _altsep = os.altsep 58 if _altsep is None and sys.platform == 'win32': 59 # My ActivePython 2.0.1 doesn't set os.altsep! What gives? 60 _altsep = '/' 61 if _altsep:
62 - def rightmost_separator(path, sep, _altsep=_altsep):
63 rfind = string.rfind 64 return max(rfind(path, sep), rfind(path, _altsep))
65 else: 66 rightmost_separator = string.rfind 67 68 # First two from the Python Cookbook, just for completeness. 69 # (Yeah, yeah, YAGNI...)
70 -def containsAny(str, set):
71 """Check whether sequence str contains ANY of the items in set.""" 72 for c in set: 73 if c in str: return 1 74 return 0
75
76 -def containsAll(str, set):
77 """Check whether sequence str contains ALL of the items in set.""" 78 for c in set: 79 if c not in str: return 0 80 return 1
81
82 -def containsOnly(str, set):
83 """Check whether sequence str contains ONLY items in set.""" 84 for c in str: 85 if c not in set: return 0 86 return 1
87
88 -def splitext(path):
89 "Same as os.path.splitext() but faster." 90 sep = rightmost_separator(path, os.sep) 91 dot = string.rfind(path, '.') 92 # An ext is only real if it has at least one non-digit char 93 if dot > sep and not containsOnly(path[dot:], "0123456789."): 94 return path[:dot],path[dot:] 95 else: 96 return path,""
97
98 -def updrive(path):
99 """ 100 Make the drive letter (if any) upper case. 101 This is useful because Windows is inconsitent on the case 102 of the drive letter, which can cause inconsistencies when 103 calculating command signatures. 104 """ 105 drive, rest = os.path.splitdrive(path) 106 if drive: 107 path = string.upper(drive) + rest 108 return path
109
110 -class CallableComposite(UserList):
111 """A simple composite callable class that, when called, will invoke all 112 of its contained callables with the same arguments."""
113 - def __call__(self, *args, **kwargs):
114 retvals = map(lambda x, args=args, kwargs=kwargs: apply(x, 115 args, 116 kwargs), 117 self.data) 118 if self.data and (len(self.data) == len(filter(callable, retvals))): 119 return self.__class__(retvals) 120 return NodeList(retvals)
121
122 -class NodeList(UserList):
123 """This class is almost exactly like a regular list of Nodes 124 (actually it can hold any object), with one important difference. 125 If you try to get an attribute from this list, it will return that 126 attribute from every item in the list. For example: 127 128 >>> someList = NodeList([ ' foo ', ' bar ' ]) 129 >>> someList.strip() 130 [ 'foo', 'bar' ] 131 """
132 - def __nonzero__(self):
133 return len(self.data) != 0
134
135 - def __str__(self):
136 return string.join(map(str, self.data))
137
138 - def __getattr__(self, name):
139 if not self.data: 140 # If there is nothing in the list, then we have no attributes to 141 # pass through, so raise AttributeError for everything. 142 raise AttributeError, "NodeList has no attribute: %s" % name 143 144 # Return a list of the attribute, gotten from every element 145 # in the list 146 attrList = map(lambda x, n=name: getattr(x, n), self.data) 147 148 # Special case. If the attribute is callable, we do not want 149 # to return a list of callables. Rather, we want to return a 150 # single callable that, when called, will invoke the function on 151 # all elements of this list. 152 if self.data and (len(self.data) == len(filter(callable, attrList))): 153 return CallableComposite(attrList) 154 return self.__class__(attrList)
155 156 _get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$') 157
158 -def get_environment_var(varstr):
159 """Given a string, first determine if it looks like a reference 160 to a single environment variable, like "$FOO" or "${FOO}". 161 If so, return that variable with no decorations ("FOO"). 162 If not, return None.""" 163 mo=_get_env_var.match(to_String(varstr)) 164 if mo: 165 var = mo.group(1) 166 if var[0] == '{': 167 return var[1:-1] 168 else: 169 return var 170 else: 171 return None
172
173 -class DisplayEngine:
174 - def __init__(self):
175 self.__call__ = self.print_it
176
177 - def print_it(self, text, append_newline=1):
178 if append_newline: text = text + '\n' 179 try: 180 sys.stdout.write(text) 181 except IOError: 182 # Stdout might be connected to a pipe that has been closed 183 # by now. The most likely reason for the pipe being closed 184 # is that the user has press ctrl-c. It this is the case, 185 # then SCons is currently shutdown. We therefore ignore 186 # IOError's here so that SCons can continue and shutdown 187 # properly so that the .sconsign is correctly written 188 # before SCons exits. 189 pass
190
191 - def dont_print(self, text, append_newline=1):
192 pass
193
194 - def set_mode(self, mode):
195 if mode: 196 self.__call__ = self.print_it 197 else: 198 self.__call__ = self.dont_print
199
200 -def render_tree(root, child_func, prune=0, margin=[0], visited={}):
201 """ 202 Render a tree of nodes into an ASCII tree view. 203 root - the root node of the tree 204 child_func - the function called to get the children of a node 205 prune - don't visit the same node twice 206 margin - the format of the left margin to use for children of root. 207 1 results in a pipe, and 0 results in no pipe. 208 visited - a dictionary of visited nodes in the current branch if not prune, 209 or in the whole tree if prune. 210 """ 211 212 rname = str(root) 213 214 children = child_func(root) 215 retval = "" 216 for pipe in margin[:-1]: 217 if pipe: 218 retval = retval + "| " 219 else: 220 retval = retval + " " 221 222 if visited.has_key(rname): 223 return retval + "+-[" + rname + "]\n" 224 225 retval = retval + "+-" + rname + "\n" 226 if not prune: 227 visited = copy.copy(visited) 228 visited[rname] = 1 229 230 for i in range(len(children)): 231 margin.append(i<len(children)-1) 232 retval = retval + render_tree(children[i], child_func, prune, margin, visited 233 ) 234 margin.pop() 235 236 return retval
237 238 IDX = lambda N: N and 1 or 0 239 291 margins = map(MMM, margin[:-1]) 292 293 children = child_func(root) 294 295 if prune and visited.has_key(rname) and children: 296 print string.join(tags + margins + ['+-[', rname, ']'], '') 297 return 298 299 print string.join(tags + margins + ['+-', rname], '') 300 301 visited[rname] = 1 302 303 if children: 304 margin.append(1) 305 map(lambda C, cf=child_func, p=prune, i=IDX(showtags), m=margin, v=visited: 306 print_tree(C, cf, p, i, m, v), 307 children[:-1]) 308 margin[-1] = 0 309 print_tree(children[-1], child_func, prune, IDX(showtags), margin, visited) 310 margin.pop() 311 312 313 314 # Functions for deciding if things are like various types, mainly to 315 # handle UserDict, UserList and UserString like their underlying types. 316 # 317 # Yes, all of this manual testing breaks polymorphism, and the real 318 # Pythonic way to do all of this would be to just try it and handle the 319 # exception, but handling the exception when it's not the right type is 320 # often too slow. 321 322 try:
323 - class mystr(str):
324 pass
325 except TypeError: 326 # An older Python version without new-style classes. 327 # 328 # The actual implementations here have been selected after timings 329 # coded up in in bench/is_types.py (from the SCons source tree, 330 # see the scons-src distribution), mostly against Python 1.5.2. 331 # Key results from those timings: 332 # 333 # -- Storing the type of the object in a variable (t = type(obj)) 334 # slows down the case where it's a native type and the first 335 # comparison will match, but nicely speeds up the case where 336 # it's a different native type. Since that's going to be 337 # common, it's a good tradeoff. 338 # 339 # -- The data show that calling isinstance() on an object that's 340 # a native type (dict, list or string) is expensive enough 341 # that checking up front for whether the object is of type 342 # InstanceType is a pretty big win, even though it does slow 343 # down the case where it really *is* an object instance a 344 # little bit.
345 - def is_Dict(obj):
346 t = type(obj) 347 return t is DictType or \ 348 (t is InstanceType and isinstance(obj, UserDict))
349
350 - def is_List(obj):
351 t = type(obj) 352 return t is ListType \ 353 or (t is InstanceType and isinstance(obj, UserList))
354
355 - def is_Sequence(obj):
356 t = type(obj) 357 return t is ListType \ 358 or t is TupleType \ 359 or (t is InstanceType and isinstance(obj, UserList))
360
361 - def is_Tuple(obj):
362 t = type(obj) 363 return t is TupleType
364 365 if hasattr(types, 'UnicodeType'):
366 - def is_String(obj):
367 t = type(obj) 368 return t is StringType \ 369 or t is UnicodeType \ 370 or (t is InstanceType and isinstance(obj, UserString))
371 else:
372 - def is_String(obj):
373 t = type(obj) 374 return t is StringType \ 375 or (t is InstanceType and isinstance(obj, UserString))
376
377 - def is_Scalar(obj):
378 return is_String(obj) or not is_Sequence(obj)
379
380 - def flatten(obj, result=None):
381 """Flatten a sequence to a non-nested list. 382 383 Flatten() converts either a single scalar or a nested sequence 384 to a non-nested list. Note that flatten() considers strings 385 to be scalars instead of sequences like Python would. 386 """ 387 if is_Scalar(obj): 388 return [obj] 389 if result is None: 390 result = [] 391 for item in obj: 392 if is_Scalar(item): 393 result.append(item) 394 else: 395 flatten_sequence(item, result) 396 return result
397
398 - def flatten_sequence(sequence, result=None):
399 """Flatten a sequence to a non-nested list. 400 401 Same as flatten(), but it does not handle the single scalar 402 case. This is slightly more efficient when one knows that 403 the sequence to flatten can not be a scalar. 404 """ 405 if result is None: 406 result = [] 407 for item in sequence: 408 if is_Scalar(item): 409 result.append(item) 410 else: 411 flatten_sequence(item, result) 412 return result
413 414 # 415 # Generic convert-to-string functions that abstract away whether or 416 # not the Python we're executing has Unicode support. The wrapper 417 # to_String_for_signature() will use a for_signature() method if the 418 # specified object has one. 419 # 420 if hasattr(types, 'UnicodeType'): 421 UnicodeType = types.UnicodeType
422 - def to_String(s):
423 if isinstance(s, UserString): 424 t = type(s.data) 425 else: 426 t = type(s) 427 if t is UnicodeType: 428 return unicode(s) 429 else: 430 return str(s)
431 else: 432 to_String = str 433
434 - def to_String_for_signature(obj):
435 try: 436 f = obj.for_signature 437 except AttributeError: 438 return to_String_for_subst(obj) 439 else: 440 return f()
441
442 - def to_String_for_subst(s):
443 if is_Sequence( s ): 444 return string.join( map(to_String_for_subst, s) ) 445 446 return to_String( s )
447 448 else: 449 # A modern Python version with new-style classes, so we can just use 450 # isinstance(). 451 # 452 # We are using the following trick to speed-up these 453 # functions. Default arguments are used to take a snapshot of the 454 # the global functions and constants used by these functions. This 455 # transforms accesses to global variable into local variables 456 # accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL). 457 458 DictTypes = (dict, UserDict) 459 ListTypes = (list, UserList) 460 SequenceTypes = (list, tuple, UserList) 461 462 # Empirically, Python versions with new-style classes all have 463 # unicode. 464 # 465 # Note that profiling data shows a speed-up when comparing 466 # explicitely with str and unicode instead of simply comparing 467 # with basestring. (at least on Python 2.5.1) 468 StringTypes = (str, unicode, UserString) 469 470 # Empirically, it is faster to check explicitely for str and 471 # unicode than for basestring. 472 BaseStringTypes = (str, unicode) 473
474 - def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
475 return isinstance(obj, DictTypes)
476
477 - def is_List(obj, isinstance=isinstance, ListTypes=ListTypes):
478 return isinstance(obj, ListTypes)
479
480 - def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes):
481 return isinstance(obj, SequenceTypes)
482
483 - def is_Tuple(obj, isinstance=isinstance, tuple=tuple):
484 return isinstance(obj, tuple)
485
486 - def is_String(obj, isinstance=isinstance, StringTypes=StringTypes):
487 return isinstance(obj, StringTypes)
488
489 - def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes):
490 # Profiling shows that there is an impressive speed-up of 2x 491 # when explicitely checking for strings instead of just not 492 # sequence when the argument (i.e. obj) is already a string. 493 # But, if obj is a not string than it is twice as fast to 494 # check only for 'not sequence'. The following code therefore 495 # assumes that the obj argument is a string must of the time. 496 return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
497
498 - def do_flatten(sequence, result, isinstance=isinstance, 499 StringTypes=StringTypes, SequenceTypes=SequenceTypes):
500 for item in sequence: 501 if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): 502 result.append(item) 503 else: 504 do_flatten(item, result)
505
506 - def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, 507 SequenceTypes=SequenceTypes, do_flatten=do_flatten):
508 """Flatten a sequence to a non-nested list. 509 510 Flatten() converts either a single scalar or a nested sequence 511 to a non-nested list. Note that flatten() considers strings 512 to be scalars instead of sequences like Python would. 513 """ 514 if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes): 515 return [obj] 516 result = [] 517 for item in obj: 518 if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): 519 result.append(item) 520 else: 521 do_flatten(item, result) 522 return result
523
524 - def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes, 525 SequenceTypes=SequenceTypes, do_flatten=do_flatten):
526 """Flatten a sequence to a non-nested list. 527 528 Same as flatten(), but it does not handle the single scalar 529 case. This is slightly more efficient when one knows that 530 the sequence to flatten can not be a scalar. 531 """ 532 result = [] 533 for item in sequence: 534 if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): 535 result.append(item) 536 else: 537 do_flatten(item, result) 538 return result
539 540 541 # 542 # Generic convert-to-string functions that abstract away whether or 543 # not the Python we're executing has Unicode support. The wrapper 544 # to_String_for_signature() will use a for_signature() method if the 545 # specified object has one. 546 #
547 - def to_String(s, 548 isinstance=isinstance, str=str, 549 UserString=UserString, BaseStringTypes=BaseStringTypes):
550 if isinstance(s,BaseStringTypes): 551 # Early out when already a string! 552 return s 553 elif isinstance(s, UserString): 554 # s.data can only be either a unicode or a regular 555 # string. Please see the UserString initializer. 556 return s.data 557 else: 558 return str(s)
559
560 - def to_String_for_subst(s, 561 isinstance=isinstance, join=string.join, str=str, to_String=to_String, 562 BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes, 563 UserString=UserString):
564 565 # Note that the test cases are sorted by order of probability. 566 if isinstance(s, BaseStringTypes): 567 return s 568 elif isinstance(s, SequenceTypes): 569 l = [] 570 for e in s: 571 l.append(to_String_for_subst(e)) 572 return join( s ) 573 elif isinstance(s, UserString): 574 # s.data can only be either a unicode or a regular 575 # string. Please see the UserString initializer. 576 return s.data 577 else: 578 return str(s)
579
580 - def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst, 581 AttributeError=AttributeError):
582 try: 583 f = obj.for_signature 584 except AttributeError: 585 return to_String_for_subst(obj) 586 else: 587 return f()
588 589 590 591 # The SCons "semi-deep" copy. 592 # 593 # This makes separate copies of lists (including UserList objects) 594 # dictionaries (including UserDict objects) and tuples, but just copies 595 # references to anything else it finds. 596 # 597 # A special case is any object that has a __semi_deepcopy__() method, 598 # which we invoke to create the copy, which is used by the BuilderDict 599 # class because of its extra initialization argument. 600 # 601 # The dispatch table approach used here is a direct rip-off from the 602 # normal Python copy module. 603 604 _semi_deepcopy_dispatch = d = {} 605
606 -def _semi_deepcopy_dict(x):
607 copy = {} 608 for key, val in x.items(): 609 # The regular Python copy.deepcopy() also deepcopies the key, 610 # as follows: 611 # 612 # copy[semi_deepcopy(key)] = semi_deepcopy(val) 613 # 614 # Doesn't seem like we need to, but we'll comment it just in case. 615 copy[key] = semi_deepcopy(val) 616 return copy
617 d[types.DictionaryType] = _semi_deepcopy_dict 618
619 -def _semi_deepcopy_list(x):
620 return map(semi_deepcopy, x)
621 d[types.ListType] = _semi_deepcopy_list 622
623 -def _semi_deepcopy_tuple(x):
624 return tuple(map(semi_deepcopy, x))
625 d[types.TupleType] = _semi_deepcopy_tuple 626
627 -def _semi_deepcopy_inst(x):
628 if hasattr(x, '__semi_deepcopy__'): 629 return x.__semi_deepcopy__() 630 elif isinstance(x, UserDict): 631 return x.__class__(_semi_deepcopy_dict(x)) 632 elif isinstance(x, UserList): 633 return x.__class__(_semi_deepcopy_list(x)) 634 else: 635 return x
636 d[types.InstanceType] = _semi_deepcopy_inst 637
638 -def semi_deepcopy(x):
639 copier = _semi_deepcopy_dispatch.get(type(x)) 640 if copier: 641 return copier(x) 642 else: 643 return x
644 645 646
647 -class Proxy:
648 """A simple generic Proxy class, forwarding all calls to 649 subject. So, for the benefit of the python newbie, what does 650 this really mean? Well, it means that you can take an object, let's 651 call it 'objA', and wrap it in this Proxy class, with a statement 652 like this 653 654 proxyObj = Proxy(objA), 655 656 Then, if in the future, you do something like this 657 658 x = proxyObj.var1, 659 660 since Proxy does not have a 'var1' attribute (but presumably objA does), 661 the request actually is equivalent to saying 662 663 x = objA.var1 664 665 Inherit from this class to create a Proxy.""" 666
667 - def __init__(self, subject):
668 """Wrap an object as a Proxy object""" 669 self.__subject = subject
670
671 - def __getattr__(self, name):
672 """Retrieve an attribute from the wrapped object. If the named 673 attribute doesn't exist, AttributeError is raised""" 674 return getattr(self.__subject, name)
675
676 - def get(self):
677 """Retrieve the entire wrapped object""" 678 return self.__subject
679
680 - def __cmp__(self, other):
681 if issubclass(other.__class__, self.__subject.__class__): 682 return cmp(self.__subject, other) 683 return cmp(self.__dict__, other.__dict__)
684 685 # attempt to load the windows registry module: 686 can_read_reg = 0 687 try: 688 import _winreg 689 690 can_read_reg = 1 691 hkey_mod = _winreg 692 693 RegOpenKeyEx = _winreg.OpenKeyEx 694 RegEnumKey = _winreg.EnumKey 695 RegEnumValue = _winreg.EnumValue 696 RegQueryValueEx = _winreg.QueryValueEx 697 RegError = _winreg.error 698 699 except ImportError: 700 try: 701 import win32api 702 import win32con 703 can_read_reg = 1 704 hkey_mod = win32con 705 706 RegOpenKeyEx = win32api.RegOpenKeyEx 707 RegEnumKey = win32api.RegEnumKey 708 RegEnumValue = win32api.RegEnumValue 709 RegQueryValueEx = win32api.RegQueryValueEx 710 RegError = win32api.error 711 712 except ImportError:
713 - class _NoError(Exception):
714 pass
715 RegError = _NoError 716 717 if can_read_reg: 718 HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT 719 HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE 720 HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER 721 HKEY_USERS = hkey_mod.HKEY_USERS 722
723 - def RegGetValue(root, key):
724 """This utility function returns a value in the registry 725 without having to open the key first. Only available on 726 Windows platforms with a version of Python that can read the 727 registry. Returns the same thing as 728 SCons.Util.RegQueryValueEx, except you just specify the entire 729 path to the value, and don't have to bother opening the key 730 first. So: 731 732 Instead of: 733 k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, 734 r'SOFTWARE\Microsoft\Windows\CurrentVersion') 735 out = SCons.Util.RegQueryValueEx(k, 736 'ProgramFilesDir') 737 738 You can write: 739 out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE, 740 r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir') 741 """ 742 # I would use os.path.split here, but it's not a filesystem 743 # path... 744 p = key.rfind('\\') + 1 745 keyp = key[:p] 746 val = key[p:] 747 k = RegOpenKeyEx(root, keyp) 748 return RegQueryValueEx(k,val)
749 750 if sys.platform == 'win32': 751
752 - def WhereIs(file, path=None, pathext=None, reject=[]):
753 if path is None: 754 try: 755 path = os.environ['PATH'] 756 except KeyError: 757 return None 758 if is_String(path): 759 path = string.split(path, os.pathsep) 760 if pathext is None: 761 try: 762 pathext = os.environ['PATHEXT'] 763 except KeyError: 764 pathext = '.COM;.EXE;.BAT;.CMD' 765 if is_String(pathext): 766 pathext = string.split(pathext, os.pathsep) 767 for ext in pathext: 768 if string.lower(ext) == string.lower(file[-len(ext):]): 769 pathext = [''] 770 break 771 if not is_List(reject) and not is_Tuple(reject): 772 reject = [reject] 773 for dir in path: 774 f = os.path.join(dir, file) 775 for ext in pathext: 776 fext = f + ext 777 if os.path.isfile(fext): 778 try: 779 reject.index(fext) 780 except ValueError: 781 return os.path.normpath(fext) 782 continue 783 return None
784 785 elif os.name == 'os2': 786
787 - def WhereIs(file, path=None, pathext=None, reject=[]):
788 if path is None: 789 try: 790 path = os.environ['PATH'] 791 except KeyError: 792 return None 793 if is_String(path): 794 path = string.split(path, os.pathsep) 795 if pathext is None: 796 pathext = ['.exe', '.cmd'] 797 for ext in pathext: 798 if string.lower(ext) == string.lower(file[-len(ext):]): 799 pathext = [''] 800 break 801 if not is_List(reject) and not is_Tuple(reject): 802 reject = [reject] 803 for dir in path: 804 f = os.path.join(dir, file) 805 for ext in pathext: 806 fext = f + ext 807 if os.path.isfile(fext): 808 try: 809 reject.index(fext) 810 except ValueError: 811 return os.path.normpath(fext) 812 continue 813 return None
814 815 else: 816
817 - def WhereIs(file, path=None, pathext=None, reject=[]):
818 import stat 819 if path is None: 820 try: 821 path = os.environ['PATH'] 822 except KeyError: 823 return None 824 if is_String(path): 825 path = string.split(path, os.pathsep) 826 if not is_List(reject) and not is_Tuple(reject): 827 reject = [reject] 828 for d in path: 829 f = os.path.join(d, file) 830 if os.path.isfile(f): 831 try: 832 st = os.stat(f) 833 except OSError: 834 # os.stat() raises OSError, not IOError if the file 835 # doesn't exist, so in this case we let IOError get 836 # raised so as to not mask possibly serious disk or 837 # network issues. 838 continue 839 if stat.S_IMODE(st[stat.ST_MODE]) & 0111: 840 try: 841 reject.index(f) 842 except ValueError: 843 return os.path.normpath(f) 844 continue 845 return None
846
847 -def PrependPath(oldpath, newpath, sep = os.pathsep, delete_existing=1):
848 """This prepends newpath elements to the given oldpath. Will only 849 add any particular path once (leaving the first one it encounters 850 and ignoring the rest, to preserve path order), and will 851 os.path.normpath and os.path.normcase all paths to help assure 852 this. This can also handle the case where the given old path 853 variable is a list instead of a string, in which case a list will 854 be returned instead of a string. 855 856 Example: 857 Old Path: "/foo/bar:/foo" 858 New Path: "/biz/boom:/foo" 859 Result: "/biz/boom:/foo:/foo/bar" 860 861 If delete_existing is 0, then adding a path that exists will 862 not move it to the beginning; it will stay where it is in the 863 list. 864 """ 865 866 orig = oldpath 867 is_list = 1 868 paths = orig 869 if not is_List(orig) and not is_Tuple(orig): 870 paths = string.split(paths, sep) 871 is_list = 0 872 873 if is_List(newpath) or is_Tuple(newpath): 874 newpaths = newpath 875 else: 876 newpaths = string.split(newpath, sep) 877 878 if not delete_existing: 879 # First uniquify the old paths, making sure to 880 # preserve the first instance (in Unix/Linux, 881 # the first one wins), and remembering them in normpaths. 882 # Then insert the new paths at the head of the list 883 # if they're not already in the normpaths list. 884 result = [] 885 normpaths = [] 886 for path in paths: 887 if not path: 888 continue 889 normpath = os.path.normpath(os.path.normcase(path)) 890 if normpath not in normpaths: 891 result.append(path) 892 normpaths.append(normpath) 893 newpaths.reverse() # since we're inserting at the head 894 for path in newpaths: 895 if not path: 896 continue 897 normpath = os.path.normpath(os.path.normcase(path)) 898 if normpath not in normpaths: 899 result.insert(0, path) 900 normpaths.append(normpath) 901 paths = result 902 903 else: 904 newpaths = newpaths + paths # prepend new paths 905 906 normpaths = [] 907 paths = [] 908 # now we add them only if they are unique 909 for path in newpaths: 910 normpath = os.path.normpath(os.path.normcase(path)) 911 if path and not normpath in normpaths: 912 paths.append(path) 913 normpaths.append(normpath) 914 915 if is_list: 916 return paths 917 else: 918 return string.join(paths, sep)
919
920 -def AppendPath(oldpath, newpath, sep = os.pathsep, delete_existing=1):
921 """This appends new path elements to the given old path. Will 922 only add any particular path once (leaving the last one it 923 encounters and ignoring the rest, to preserve path order), and 924 will os.path.normpath and os.path.normcase all paths to help 925 assure this. This can also handle the case where the given old 926 path variable is a list instead of a string, in which case a list 927 will be returned instead of a string. 928 929 Example: 930 Old Path: "/foo/bar:/foo" 931 New Path: "/biz/boom:/foo" 932 Result: "/foo/bar:/biz/boom:/foo" 933 934 If delete_existing is 0, then adding a path that exists 935 will not move it to the end; it will stay where it is in the list. 936 """ 937 938 orig = oldpath 939 is_list = 1 940 paths = orig 941 if not is_List(orig) and not is_Tuple(orig): 942 paths = string.split(paths, sep) 943 is_list = 0 944 945 if is_List(newpath) or is_Tuple(newpath): 946 newpaths = newpath 947 else: 948 newpaths = string.split(newpath, sep) 949 950 if not delete_existing: 951 # add old paths to result, then 952 # add new paths if not already present 953 # (I thought about using a dict for normpaths for speed, 954 # but it's not clear hashing the strings would be faster 955 # than linear searching these typically short lists.) 956 result = [] 957 normpaths = [] 958 for path in paths: 959 if not path: 960 continue 961 result.append(path) 962 normpaths.append(os.path.normpath(os.path.normcase(path))) 963 for path in newpaths: 964 if not path: 965 continue 966 normpath = os.path.normpath(os.path.normcase(path)) 967 if normpath not in normpaths: 968 result.append(path) 969 normpaths.append(normpath) 970 paths = result 971 else: 972 # start w/ new paths, add old ones if not present, 973 # then reverse. 974 newpaths = paths + newpaths # append new paths 975 newpaths.reverse() 976 977 normpaths = [] 978 paths = [] 979 # now we add them only if they are unique 980 for path in newpaths: 981 normpath = os.path.normpath(os.path.normcase(path)) 982 if path and not normpath in normpaths: 983 paths.append(path) 984 normpaths.append(normpath) 985 paths.reverse() 986 987 if is_list: 988 return paths 989 else: 990 return string.join(paths, sep)
991 992 if sys.platform == 'cygwin':
993 - def get_native_path(path):
994 """Transforms an absolute path into a native path for the system. In 995 Cygwin, this converts from a Cygwin path to a Windows one.""" 996 return string.replace(os.popen('cygpath -w ' + path).read(), '\n', '')
997 else:
998 - def get_native_path(path):
999 """Transforms an absolute path into a native path for the system. 1000 Non-Cygwin version, just leave the path alone.""" 1001 return path
1002 1003 display = DisplayEngine() 1004
1005 -def Split(arg):
1006 if is_List(arg) or is_Tuple(arg): 1007 return arg 1008 elif is_String(arg): 1009 return string.split(arg) 1010 else: 1011 return [arg]
1012
1013 -class CLVar(UserList):
1014 """A class for command-line construction variables. 1015 1016 This is a list that uses Split() to split an initial string along 1017 white-space arguments, and similarly to split any strings that get 1018 added. This allows us to Do the Right Thing with Append() and 1019 Prepend() (as well as straight Python foo = env['VAR'] + 'arg1 1020 arg2') regardless of whether a user adds a list or a string to a 1021 command-line construction variable. 1022 """
1023 - def __init__(self, seq = []):
1024 UserList.__init__(self, Split(seq))
1025 - def __coerce__(self, other):
1026 return (self, CLVar(other))
1027 - def __str__(self):
1028 return string.join(self.data)
1029 1030 # A dictionary that preserves the order in which items are added. 1031 # Submitted by David Benjamin to ActiveState's Python Cookbook web site: 1032 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 1033 # Including fixes/enhancements from the follow-on discussions.
1034 -class OrderedDict(UserDict):
1035 - def __init__(self, dict = None):
1036 self._keys = [] 1037 UserDict.__init__(self, dict)
1038
1039 - def __delitem__(self, key):
1040 UserDict.__delitem__(self, key) 1041 self._keys.remove(key)
1042
1043 - def __setitem__(self, key, item):
1044 UserDict.__setitem__(self, key, item) 1045 if key not in self._keys: self._keys.append(key)
1046
1047 - def clear(self):
1048 UserDict.clear(self) 1049 self._keys = []
1050
1051 - def copy(self):
1052 dict = OrderedDict() 1053 dict.update(self) 1054 return dict
1055
1056 - def items(self):
1057 return zip(self._keys, self.values())
1058
1059 - def keys(self):
1060 return self._keys[:]
1061
1062 - def popitem(self):
1063 try: 1064 key = self._keys[-1] 1065 except IndexError: 1066 raise KeyError('dictionary is empty') 1067 1068 val = self[key] 1069 del self[key] 1070 1071 return (key, val)
1072
1073 - def setdefault(self, key, failobj = None):
1074 UserDict.setdefault(self, key, failobj) 1075 if key not in self._keys: self._keys.append(key)
1076
1077 - def update(self, dict):
1078 for (key, val) in dict.items(): 1079 self.__setitem__(key, val)
1080
1081 - def values(self):
1082 return map(self.get, self._keys)
1083
1084 -class Selector(OrderedDict):
1085 """A callable ordered dictionary that maps file suffixes to 1086 dictionary values. We preserve the order in which items are added 1087 so that get_suffix() calls always return the first suffix added."""
1088 - def __call__(self, env, source):
1089 try: 1090 ext = source[0].suffix 1091 except IndexError: 1092 ext = "" 1093 try: 1094 return self[ext] 1095 except KeyError: 1096 # Try to perform Environment substitution on the keys of 1097 # the dictionary before giving up. 1098 s_dict = {} 1099 for (k,v) in self.items(): 1100 if not k is None: 1101 s_k = env.subst(k) 1102 if s_dict.has_key(s_k): 1103 # We only raise an error when variables point 1104 # to the same suffix. If one suffix is literal 1105 # and a variable suffix contains this literal, 1106 # the literal wins and we don't raise an error. 1107 raise KeyError, (s_dict[s_k][0], k, s_k) 1108 s_dict[s_k] = (k,v) 1109 try: 1110 return s_dict[ext][1] 1111 except KeyError: 1112 try: 1113 return self[None] 1114 except KeyError: 1115 return None
1116 1117 1118 if sys.platform == 'cygwin': 1119 # On Cygwin, os.path.normcase() lies, so just report back the 1120 # fact that the underlying Windows OS is case-insensitive.
1121 - def case_sensitive_suffixes(s1, s2):
1122 return 0
1123 else:
1124 - def case_sensitive_suffixes(s1, s2):
1125 return (os.path.normcase(s1) != os.path.normcase(s2))
1126
1127 -def adjustixes(fname, pre, suf, ensure_suffix=False):
1128 if pre: 1129 path, fn = os.path.split(os.path.normpath(fname)) 1130 if fn[:len(pre)] != pre: 1131 fname = os.path.join(path, pre + fn) 1132 # Only append a suffix if the suffix we're going to add isn't already 1133 # there, and if either we've been asked to ensure the specific suffix 1134 # is present or there's no suffix on it at all. 1135 if suf and fname[-len(suf):] != suf and \ 1136 (ensure_suffix or not splitext(fname)[1]): 1137 fname = fname + suf 1138 return fname
1139 1140 1141 1142 # From Tim Peters, 1143 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 1144 # ASPN: Python Cookbook: Remove duplicates from a sequence 1145 # (Also in the printed Python Cookbook.) 1146
1147 -def unique(s):
1148 """Return a list of the elements in s, but without duplicates. 1149 1150 For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3], 1151 unique("abcabc") some permutation of ["a", "b", "c"], and 1152 unique(([1, 2], [2, 3], [1, 2])) some permutation of 1153 [[2, 3], [1, 2]]. 1154 1155 For best speed, all sequence elements should be hashable. Then 1156 unique() will usually work in linear time. 1157 1158 If not possible, the sequence elements should enjoy a total 1159 ordering, and if list(s).sort() doesn't raise TypeError it's 1160 assumed that they do enjoy a total ordering. Then unique() will 1161 usually work in O(N*log2(N)) time. 1162 1163 If that's not possible either, the sequence elements must support 1164 equality-testing. Then unique() will usually work in quadratic 1165 time. 1166 """ 1167 1168 n = len(s) 1169 if n == 0: 1170 return [] 1171 1172 # Try using a dict first, as that's the fastest and will usually 1173 # work. If it doesn't work, it will usually fail quickly, so it 1174 # usually doesn't cost much to *try* it. It requires that all the 1175 # sequence elements be hashable, and support equality comparison. 1176 u = {} 1177 try: 1178 for x in s: 1179 u[x] = 1 1180 except TypeError: 1181 pass # move on to the next method 1182 else: 1183 return u.keys() 1184 del u 1185 1186 # We can't hash all the elements. Second fastest is to sort, 1187 # which brings the equal elements together; then duplicates are 1188 # easy to weed out in a single pass. 1189 # NOTE: Python's list.sort() was designed to be efficient in the 1190 # presence of many duplicate elements. This isn't true of all 1191 # sort functions in all languages or libraries, so this approach 1192 # is more effective in Python than it may be elsewhere. 1193 try: 1194 t = list(s) 1195 t.sort() 1196 except TypeError: 1197 pass # move on to the next method 1198 else: 1199 assert n > 0 1200 last = t[0] 1201 lasti = i = 1 1202 while i < n: 1203 if t[i] != last: 1204 t[lasti] = last = t[i] 1205 lasti = lasti + 1 1206 i = i + 1 1207 return t[:lasti] 1208 del t 1209 1210 # Brute force is all that's left. 1211 u = [] 1212 for x in s: 1213 if x not in u: 1214 u.append(x) 1215 return u
1216 1217 1218 1219 # From Alex Martelli, 1220 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 1221 # ASPN: Python Cookbook: Remove duplicates from a sequence 1222 # First comment, dated 2001/10/13. 1223 # (Also in the printed Python Cookbook.) 1224
1225 -def uniquer(seq, idfun=None):
1226 if idfun is None: 1227 def idfun(x): return x 1228 seen = {} 1229 result = [] 1230 for item in seq: 1231 marker = idfun(item) 1232 # in old Python versions: 1233 # if seen.has_key(marker) 1234 # but in new ones: 1235 if marker in seen: continue 1236 seen[marker] = 1 1237 result.append(item) 1238 return result
1239 1240 # A more efficient implementation of Alex's uniquer(), this avoids the 1241 # idfun() argument and function-call overhead by assuming that all 1242 # items in the sequence are hashable. 1243
1244 -def uniquer_hashables(seq):
1245 seen = {} 1246 result = [] 1247 for item in seq: 1248 #if not item in seen: 1249 if not seen.has_key(item): 1250 seen[item] = 1 1251 result.append(item) 1252 return result
1253 1254 1255 1256 # Much of the logic here was originally based on recipe 4.9 from the 1257 # Python CookBook, but we had to dumb it way down for Python 1.5.2.
1258 -class LogicalLines:
1259
1260 - def __init__(self, fileobj):
1261 self.fileobj = fileobj
1262
1263 - def readline(self):
1264 result = [] 1265 while 1: 1266 line = self.fileobj.readline() 1267 if not line: 1268 break 1269 if line[-2:] == '\\\n': 1270 result.append(line[:-2]) 1271 else: 1272 result.append(line) 1273 break 1274 return string.join(result, '')
1275
1276 - def readlines(self):
1277 result = [] 1278 while 1: 1279 line = self.readline() 1280 if not line: 1281 break 1282 result.append(line) 1283 return result
1284 1285 1286
1287 -class UniqueList(UserList):
1288 - def __init__(self, seq = []):
1289 UserList.__init__(self, seq) 1290 self.unique = True
1291 - def __make_unique(self):
1292 if not self.unique: 1293 self.data = uniquer_hashables(self.data) 1294 self.unique = True
1295 - def __lt__(self, other):
1296 self.__make_unique() 1297 return UserList.__lt__(self, other)
1298 - def __le__(self, other):
1299 self.__make_unique() 1300 return UserList.__le__(self, other)
1301 - def __eq__(self, other):
1302 self.__make_unique() 1303 return UserList.__eq__(self, other)
1304 - def __ne__(self, other):
1305 self.__make_unique() 1306 return UserList.__ne__(self, other)
1307 - def __gt__(self, other):
1308 self.__make_unique() 1309 return UserList.__gt__(self, other)
1310 - def __ge__(self, other):
1311 self.__make_unique() 1312 return UserList.__ge__(self, other)
1313 - def __cmp__(self, other):
1314 self.__make_unique() 1315 return UserList.__cmp__(self, other)
1316 - def __len__(self):
1317 self.__make_unique() 1318 return UserList.__len__(self)
1319 - def __getitem__(self, i):
1320 self.__make_unique() 1321 return UserList.__getitem__(self, i)
1322 - def __setitem__(self, i, item):
1323 UserList.__setitem__(self, i, item) 1324 self.unique = False
1325 - def __getslice__(self, i, j):
1326 self.__make_unique() 1327 return UserList.__getslice__(self, i, j)
1328 - def __setslice__(self, i, j, other):
1329 UserList.__setslice__(self, i, j, other) 1330 self.unique = False
1331 - def __add__(self, other):
1332 result = UserList.__add__(self, other) 1333 result.unique = False 1334 return result
1335 - def __radd__(self, other):
1336 result = UserList.__radd__(self, other) 1337 result.unique = False 1338 return result
1339 - def __iadd__(self, other):
1340 result = UserList.__iadd__(self, other) 1341 result.unique = False 1342 return result
1343 - def __mul__(self, other):
1344 result = UserList.__mul__(self, other) 1345 result.unique = False 1346 return result
1347 - def __rmul__(self, other):
1348 result = UserList.__rmul__(self, other) 1349 result.unique = False 1350 return result
1351 - def __imul__(self, other):
1352 result = UserList.__imul__(self, other) 1353 result.unique = False 1354 return result
1355 - def append(self, item):
1356 UserList.append(self, item) 1357 self.unique = False
1358 - def insert(self, i):
1359 UserList.insert(self, i) 1360 self.unique = False
1361 - def count(self, item):
1362 self.__make_unique() 1363 return UserList.count(self, item)
1364 - def index(self, item):
1365 self.__make_unique() 1366 return UserList.index(self, item)
1367 - def reverse(self):
1368 self.__make_unique() 1369 UserList.reverse(self)
1370 - def sort(self, *args, **kwds):
1371 self.__make_unique() 1372 #return UserList.sort(self, *args, **kwds) 1373 return apply(UserList.sort, (self,)+args, kwds)
1374 - def extend(self, other):
1375 UserList.extend(self, other) 1376 self.unique = False
1377 1378 1379
1380 -class Unbuffered:
1381 """ 1382 A proxy class that wraps a file object, flushing after every write, 1383 and delegating everything else to the wrapped object. 1384 """
1385 - def __init__(self, file):
1386 self.file = file
1387 - def write(self, arg):
1388 try: 1389 self.file.write(arg) 1390 self.file.flush() 1391 except IOError: 1392 # Stdout might be connected to a pipe that has been closed 1393 # by now. The most likely reason for the pipe being closed 1394 # is that the user has press ctrl-c. It this is the case, 1395 # then SCons is currently shutdown. We therefore ignore 1396 # IOError's here so that SCons can continue and shutdown 1397 # properly so that the .sconsign is correctly written 1398 # before SCons exits. 1399 pass
1400 - def __getattr__(self, attr):
1401 return getattr(self.file, attr)
1402
1403 -def make_path_relative(path):
1404 """ makes an absolute path name to a relative pathname. 1405 """ 1406 if os.path.isabs(path): 1407 drive_s,path = os.path.splitdrive(path) 1408 1409 import re 1410 if not drive_s: 1411 path=re.compile("/*(.*)").findall(path)[0] 1412 else: 1413 path=path[1:] 1414 1415 assert( not os.path.isabs( path ) ), path 1416 return path
1417 1418 1419 1420 # The original idea for AddMethod() and RenameFunction() come from the 1421 # following post to the ActiveState Python Cookbook: 1422 # 1423 # ASPN: Python Cookbook : Install bound methods in an instance 1424 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613 1425 # 1426 # That code was a little fragile, though, so the following changes 1427 # have been wrung on it: 1428 # 1429 # * Switched the installmethod() "object" and "function" arguments, 1430 # so the order reflects that the left-hand side is the thing being 1431 # "assigned to" and the right-hand side is the value being assigned. 1432 # 1433 # * Changed explicit type-checking to the "try: klass = object.__class__" 1434 # block in installmethod() below so that it still works with the 1435 # old-style classes that SCons uses. 1436 # 1437 # * Replaced the by-hand creation of methods and functions with use of 1438 # the "new" module, as alluded to in Alex Martelli's response to the 1439 # following Cookbook post: 1440 # 1441 # ASPN: Python Cookbook : Dynamically added methods to a class 1442 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 1443
1444 -def AddMethod(object, function, name = None):
1445 """ 1446 Adds either a bound method to an instance or an unbound method to 1447 a class. If name is ommited the name of the specified function 1448 is used by default. 1449 Example: 1450 a = A() 1451 def f(self, x, y): 1452 self.z = x + y 1453 AddMethod(f, A, "add") 1454 a.add(2, 4) 1455 print a.z 1456 AddMethod(lambda self, i: self.l[i], a, "listIndex") 1457 print a.listIndex(5) 1458 """ 1459 import new 1460 1461 if name is None: 1462 name = function.func_name 1463 else: 1464 function = RenameFunction(function, name) 1465 1466 try: 1467 klass = object.__class__ 1468 except AttributeError: 1469 # "object" is really a class, so it gets an unbound method. 1470 object.__dict__[name] = new.instancemethod(function, None, object) 1471 else: 1472 # "object" is really an instance, so it gets a bound method. 1473 object.__dict__[name] = new.instancemethod(function, object, klass)
1474
1475 -def RenameFunction(function, name):
1476 """ 1477 Returns a function identical to the specified function, but with 1478 the specified name. 1479 """ 1480 import new 1481 1482 # Compatibility for Python 1.5 and 2.1. Can be removed in favor of 1483 # passing function.func_defaults directly to new.function() once 1484 # we base on Python 2.2 or later. 1485 func_defaults = function.func_defaults 1486 if func_defaults is None: 1487 func_defaults = () 1488 1489 return new.function(function.func_code, 1490 function.func_globals, 1491 name, 1492 func_defaults)
1493 1494 1495 md5 = False
1496 -def MD5signature(s):
1497 return str(s)
1498
1499 -def MD5filesignature(fname, chunksize=65536):
1500 f = open(fname, "rb") 1501 result = f.read() 1502 f.close() 1503 return result
1504 1505 try: 1506 import hashlib 1507 except ImportError: 1508 pass 1509 else: 1510 if hasattr(hashlib, 'md5'): 1511 md5 = True
1512 - def MD5signature(s):
1513 m = hashlib.md5() 1514 m.update(str(s)) 1515 return m.hexdigest()
1516
1517 - def MD5filesignature(fname, chunksize=65536):
1518 m = hashlib.md5() 1519 f = open(fname, "rb") 1520 while 1: 1521 blck = f.read(chunksize) 1522 if not blck: 1523 break 1524 m.update(str(blck)) 1525 f.close() 1526 return m.hexdigest()
1527
1528 -def MD5collect(signatures):
1529 """ 1530 Collects a list of signatures into an aggregate signature. 1531 1532 signatures - a list of signatures 1533 returns - the aggregate signature 1534 """ 1535 if len(signatures) == 1: 1536 return signatures[0] 1537 else: 1538 return MD5signature(string.join(signatures, ', '))
1539 1540 1541 1542 # From Dinu C. Gherman, 1543 # Python Cookbook, second edition, recipe 6.17, p. 277. 1544 # Also: 1545 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 1546 # ASPN: Python Cookbook: Null Object Design Pattern 1547
1548 -class Null:
1549 """ Null objects always and reliably "do nothging." """ 1550
1551 - def __new__(cls, *args, **kwargs):
1552 if not '_inst' in vars(cls): 1553 #cls._inst = type.__new__(cls, *args, **kwargs) 1554 cls._inst = apply(type.__new__, (cls,) + args, kwargs) 1555 return cls._inst
1556 - def __init__(self, *args, **kwargs):
1557 pass
1558 - def __call__(self, *args, **kwargs):
1559 return self
1560 - def __repr__(self):
1561 return "Null()"
1562 - def __nonzero__(self):
1563 return False
1564 - def __getattr__(self, mname):
1565 return self
1566 - def __setattr__(self, name, value):
1567 return self
1568 - def __delattr__(self, name):
1569 return self
1570 1571 1572 1573 del __revision__ 1574