11# pylint: skip-file
22
3- # Copyright (c) 2010-2017 Benjamin Peterson
3+ # Copyright (c) 2010-2020 Benjamin Peterson
44#
55# Permission is hereby granted, free of charge, to any person obtaining a copy
66# of this software and associated documentation files (the "Software"), to deal
3131import types
3232
3333__author__ = "Benjamin Peterson <benjamin@python.org>"
34- __version__ = "1.11 .0"
34+ __version__ = "1.16 .0"
3535
3636
3737# Useful for very coarse version differentiation.
@@ -77,6 +77,11 @@ def __len__(self):
7777 # https://github.com/dpkp/kafka-python/pull/979#discussion_r100403389
7878 # del X
7979
80+ if PY34 :
81+ from importlib .util import spec_from_loader
82+ else :
83+ spec_from_loader = None
84+
8085
8186def _add_doc (func , doc ):
8287 """Add documentation to a function."""
@@ -192,6 +197,11 @@ def find_module(self, fullname, path=None):
192197 return self
193198 return None
194199
200+ def find_spec (self , fullname , path , target = None ):
201+ if fullname in self .known_modules :
202+ return spec_from_loader (fullname , self )
203+ return None
204+
195205 def __get_module (self , fullname ):
196206 try :
197207 return self .known_modules [fullname ]
@@ -229,6 +239,12 @@ def get_code(self, fullname):
229239 return None
230240 get_source = get_code # same as get_code
231241
242+ def create_module (self , spec ):
243+ return self .load_module (spec .name )
244+
245+ def exec_module (self , module ):
246+ pass
247+
232248_importer = _SixMetaPathImporter (__name__ )
233249
234250
@@ -253,17 +269,19 @@ class _MovedItems(_LazyModule):
253269 MovedAttribute ("reduce" , "__builtin__" , "functools" ),
254270 MovedAttribute ("shlex_quote" , "pipes" , "shlex" , "quote" ),
255271 MovedAttribute ("StringIO" , "StringIO" , "io" ),
256- MovedAttribute ("UserDict" , "UserDict" , "collections" ),
272+ MovedAttribute ("UserDict" , "UserDict" , "collections" , "IterableUserDict" , "UserDict" ),
257273 MovedAttribute ("UserList" , "UserList" , "collections" ),
258274 MovedAttribute ("UserString" , "UserString" , "collections" ),
259275 MovedAttribute ("xrange" , "__builtin__" , "builtins" , "xrange" , "range" ),
260276 MovedAttribute ("zip" , "itertools" , "builtins" , "izip" , "zip" ),
261277 MovedAttribute ("zip_longest" , "itertools" , "itertools" , "izip_longest" , "zip_longest" ),
262278 MovedModule ("builtins" , "__builtin__" ),
263279 MovedModule ("configparser" , "ConfigParser" ),
280+ MovedModule ("collections_abc" , "collections" , "collections.abc" if sys .version_info >= (3 , 3 ) else "collections" ),
264281 MovedModule ("copyreg" , "copy_reg" ),
265282 MovedModule ("dbm_gnu" , "gdbm" , "dbm.gnu" ),
266- MovedModule ("_dummy_thread" , "dummy_thread" , "_dummy_thread" ),
283+ MovedModule ("dbm_ndbm" , "dbm" , "dbm.ndbm" ),
284+ MovedModule ("_dummy_thread" , "dummy_thread" , "_dummy_thread" if sys .version_info < (3 , 9 ) else "_thread" ),
267285 MovedModule ("http_cookiejar" , "cookielib" , "http.cookiejar" ),
268286 MovedModule ("http_cookies" , "Cookie" , "http.cookies" ),
269287 MovedModule ("html_entities" , "htmlentitydefs" , "html.entities" ),
@@ -643,13 +661,16 @@ def u(s):
643661 import io
644662 StringIO = io .StringIO
645663 BytesIO = io .BytesIO
664+ del io
646665 _assertCountEqual = "assertCountEqual"
647666 if sys .version_info [1 ] <= 1 :
648667 _assertRaisesRegex = "assertRaisesRegexp"
649668 _assertRegex = "assertRegexpMatches"
669+ _assertNotRegex = "assertNotRegexpMatches"
650670 else :
651671 _assertRaisesRegex = "assertRaisesRegex"
652672 _assertRegex = "assertRegex"
673+ _assertNotRegex = "assertNotRegex"
653674else :
654675 def b (s ):
655676 return s
@@ -671,6 +692,7 @@ def indexbytes(buf, i):
671692 _assertCountEqual = "assertItemsEqual"
672693 _assertRaisesRegex = "assertRaisesRegexp"
673694 _assertRegex = "assertRegexpMatches"
695+ _assertNotRegex = "assertNotRegexpMatches"
674696_add_doc (b , """Byte literal""" )
675697_add_doc (u , """Text literal""" )
676698
@@ -687,6 +709,10 @@ def assertRegex(self, *args, **kwargs):
687709 return getattr (self , _assertRegex )(* args , ** kwargs )
688710
689711
712+ def assertNotRegex (self , * args , ** kwargs ):
713+ return getattr (self , _assertNotRegex )(* args , ** kwargs )
714+
715+
690716if PY3 :
691717 exec_ = getattr (moves .builtins , "exec" )
692718
@@ -722,16 +748,7 @@ def exec_(_code_, _globs_=None, _locs_=None):
722748""" )
723749
724750
725- if sys .version_info [:2 ] == (3 , 2 ):
726- exec_ ("""def raise_from(value, from_value):
727- try:
728- if from_value is None:
729- raise value
730- raise value from from_value
731- finally:
732- value = None
733- """ )
734- elif sys .version_info [:2 ] > (3 , 2 ):
751+ if sys .version_info [:2 ] > (3 ,):
735752 exec_ ("""def raise_from(value, from_value):
736753 try:
737754 raise value from from_value
@@ -811,13 +828,33 @@ def print_(*args, **kwargs):
811828_add_doc (reraise , """Reraise an exception.""" )
812829
813830if sys .version_info [0 :2 ] < (3 , 4 ):
831+ # This does exactly the same what the :func:`py3:functools.update_wrapper`
832+ # function does on Python versions after 3.2. It sets the ``__wrapped__``
833+ # attribute on ``wrapper`` object and it doesn't raise an error if any of
834+ # the attributes mentioned in ``assigned`` and ``updated`` are missing on
835+ # ``wrapped`` object.
836+ def _update_wrapper (wrapper , wrapped ,
837+ assigned = functools .WRAPPER_ASSIGNMENTS ,
838+ updated = functools .WRAPPER_UPDATES ):
839+ for attr in assigned :
840+ try :
841+ value = getattr (wrapped , attr )
842+ except AttributeError :
843+ continue
844+ else :
845+ setattr (wrapper , attr , value )
846+ for attr in updated :
847+ getattr (wrapper , attr ).update (getattr (wrapped , attr , {}))
848+ wrapper .__wrapped__ = wrapped
849+ return wrapper
850+ _update_wrapper .__doc__ = functools .update_wrapper .__doc__
851+
814852 def wraps (wrapped , assigned = functools .WRAPPER_ASSIGNMENTS ,
815853 updated = functools .WRAPPER_UPDATES ):
816- def wrapper (f ):
817- f = functools .wraps (wrapped , assigned , updated )(f )
818- f .__wrapped__ = wrapped
819- return f
820- return wrapper
854+ return functools .partial (_update_wrapper , wrapped = wrapped ,
855+ assigned = assigned , updated = updated )
856+ wraps .__doc__ = functools .wraps .__doc__
857+
821858else :
822859 wraps = functools .wraps
823860
@@ -830,7 +867,15 @@ def with_metaclass(meta, *bases):
830867 class metaclass (type ):
831868
832869 def __new__ (cls , name , this_bases , d ):
833- return meta (name , bases , d )
870+ if sys .version_info [:2 ] >= (3 , 7 ):
871+ # This version introduced PEP 560 that requires a bit
872+ # of extra care (we mimic what is done by __build_class__).
873+ resolved_bases = types .resolve_bases (bases )
874+ if resolved_bases is not bases :
875+ d ['__orig_bases__' ] = bases
876+ else :
877+ resolved_bases = bases
878+ return meta (name , resolved_bases , d )
834879
835880 @classmethod
836881 def __prepare__ (cls , name , this_bases ):
@@ -850,13 +895,75 @@ def wrapper(cls):
850895 orig_vars .pop (slots_var )
851896 orig_vars .pop ('__dict__' , None )
852897 orig_vars .pop ('__weakref__' , None )
898+ if hasattr (cls , '__qualname__' ):
899+ orig_vars ['__qualname__' ] = cls .__qualname__
853900 return metaclass (cls .__name__ , cls .__bases__ , orig_vars )
854901 return wrapper
855902
856903
904+ def ensure_binary (s , encoding = 'utf-8' , errors = 'strict' ):
905+ """Coerce **s** to six.binary_type.
906+
907+ For Python 2:
908+ - `unicode` -> encoded to `str`
909+ - `str` -> `str`
910+
911+ For Python 3:
912+ - `str` -> encoded to `bytes`
913+ - `bytes` -> `bytes`
914+ """
915+ if isinstance (s , binary_type ):
916+ return s
917+ if isinstance (s , text_type ):
918+ return s .encode (encoding , errors )
919+ raise TypeError ("not expecting type '%s'" % type (s ))
920+
921+
922+ def ensure_str (s , encoding = 'utf-8' , errors = 'strict' ):
923+ """Coerce *s* to `str`.
924+
925+ For Python 2:
926+ - `unicode` -> encoded to `str`
927+ - `str` -> `str`
928+
929+ For Python 3:
930+ - `str` -> `str`
931+ - `bytes` -> decoded to `str`
932+ """
933+ # Optimization: Fast return for the common case.
934+ if type (s ) is str :
935+ return s
936+ if PY2 and isinstance (s , text_type ):
937+ return s .encode (encoding , errors )
938+ elif PY3 and isinstance (s , binary_type ):
939+ return s .decode (encoding , errors )
940+ elif not isinstance (s , (text_type , binary_type )):
941+ raise TypeError ("not expecting type '%s'" % type (s ))
942+ return s
943+
944+
945+ def ensure_text (s , encoding = 'utf-8' , errors = 'strict' ):
946+ """Coerce *s* to six.text_type.
947+
948+ For Python 2:
949+ - `unicode` -> `unicode`
950+ - `str` -> `unicode`
951+
952+ For Python 3:
953+ - `str` -> `str`
954+ - `bytes` -> decoded to `str`
955+ """
956+ if isinstance (s , binary_type ):
957+ return s .decode (encoding , errors )
958+ elif isinstance (s , text_type ):
959+ return s
960+ else :
961+ raise TypeError ("not expecting type '%s'" % type (s ))
962+
963+
857964def python_2_unicode_compatible (klass ):
858965 """
859- A decorator that defines __unicode__ and __str__ methods under Python 2.
966+ A class decorator that defines __unicode__ and __str__ methods under Python 2.
860967 Under Python 3 it does nothing.
861968
862969 To support Python 2 and 3 with a single code base, define a __str__ method
0 commit comments