1
- # Copyright (c) 2010-2017 Benjamin Peterson
1
+ # Copyright (c) 2010-2024 Benjamin Peterson
2
2
#
3
3
# Permission is hereby granted, free of charge, to any person obtaining a copy
4
4
# of this software and associated documentation files (the "Software"), to deal
29
29
import types
30
30
31
31
__author__ = "Benjamin Peterson <[email protected] >"
32
- __version__ = "1.11 .0"
32
+ __version__ = "1.17 .0"
33
33
34
34
35
35
# Useful for very coarse version differentiation.
@@ -71,6 +71,11 @@ def __len__(self):
71
71
MAXSIZE = int ((1 << 63 ) - 1 )
72
72
del X
73
73
74
+ if PY34 :
75
+ from importlib .util import spec_from_loader
76
+ else :
77
+ spec_from_loader = None
78
+
74
79
75
80
def _add_doc (func , doc ):
76
81
"""Add documentation to a function."""
@@ -186,6 +191,11 @@ def find_module(self, fullname, path=None):
186
191
return self
187
192
return None
188
193
194
+ def find_spec (self , fullname , path , target = None ):
195
+ if fullname in self .known_modules :
196
+ return spec_from_loader (fullname , self )
197
+ return None
198
+
189
199
def __get_module (self , fullname ):
190
200
try :
191
201
return self .known_modules [fullname ]
@@ -223,6 +233,12 @@ def get_code(self, fullname):
223
233
return None
224
234
get_source = get_code # same as get_code
225
235
236
+ def create_module (self , spec ):
237
+ return self .load_module (spec .name )
238
+
239
+ def exec_module (self , module ):
240
+ pass
241
+
226
242
_importer = _SixMetaPathImporter (__name__ )
227
243
228
244
@@ -247,17 +263,19 @@ class _MovedItems(_LazyModule):
247
263
MovedAttribute ("reduce" , "__builtin__" , "functools" ),
248
264
MovedAttribute ("shlex_quote" , "pipes" , "shlex" , "quote" ),
249
265
MovedAttribute ("StringIO" , "StringIO" , "io" ),
250
- MovedAttribute ("UserDict" , "UserDict" , "collections" ),
266
+ MovedAttribute ("UserDict" , "UserDict" , "collections" , "IterableUserDict" , "UserDict" ),
251
267
MovedAttribute ("UserList" , "UserList" , "collections" ),
252
268
MovedAttribute ("UserString" , "UserString" , "collections" ),
253
269
MovedAttribute ("xrange" , "__builtin__" , "builtins" , "xrange" , "range" ),
254
270
MovedAttribute ("zip" , "itertools" , "builtins" , "izip" , "zip" ),
255
271
MovedAttribute ("zip_longest" , "itertools" , "itertools" , "izip_longest" , "zip_longest" ),
256
272
MovedModule ("builtins" , "__builtin__" ),
257
273
MovedModule ("configparser" , "ConfigParser" ),
274
+ MovedModule ("collections_abc" , "collections" , "collections.abc" if sys .version_info >= (3 , 3 ) else "collections" ),
258
275
MovedModule ("copyreg" , "copy_reg" ),
259
276
MovedModule ("dbm_gnu" , "gdbm" , "dbm.gnu" ),
260
- MovedModule ("_dummy_thread" , "dummy_thread" , "_dummy_thread" ),
277
+ MovedModule ("dbm_ndbm" , "dbm" , "dbm.ndbm" ),
278
+ MovedModule ("_dummy_thread" , "dummy_thread" , "_dummy_thread" if sys .version_info < (3 , 9 ) else "_thread" ),
261
279
MovedModule ("http_cookiejar" , "cookielib" , "http.cookiejar" ),
262
280
MovedModule ("http_cookies" , "Cookie" , "http.cookies" ),
263
281
MovedModule ("html_entities" , "htmlentitydefs" , "html.entities" ),
@@ -417,12 +435,17 @@ class Module_six_moves_urllib_request(_LazyModule):
417
435
MovedAttribute ("HTTPErrorProcessor" , "urllib2" , "urllib.request" ),
418
436
MovedAttribute ("urlretrieve" , "urllib" , "urllib.request" ),
419
437
MovedAttribute ("urlcleanup" , "urllib" , "urllib.request" ),
420
- MovedAttribute ("URLopener" , "urllib" , "urllib.request" ),
421
- MovedAttribute ("FancyURLopener" , "urllib" , "urllib.request" ),
422
438
MovedAttribute ("proxy_bypass" , "urllib" , "urllib.request" ),
423
439
MovedAttribute ("parse_http_list" , "urllib2" , "urllib.request" ),
424
440
MovedAttribute ("parse_keqv_list" , "urllib2" , "urllib.request" ),
425
441
]
442
+ if sys .version_info [:2 ] < (3 , 14 ):
443
+ _urllib_request_moved_attributes .extend (
444
+ [
445
+ MovedAttribute ("URLopener" , "urllib" , "urllib.request" ),
446
+ MovedAttribute ("FancyURLopener" , "urllib" , "urllib.request" ),
447
+ ]
448
+ )
426
449
for attr in _urllib_request_moved_attributes :
427
450
setattr (Module_six_moves_urllib_request , attr .name , attr )
428
451
del attr
@@ -637,13 +660,16 @@ def u(s):
637
660
import io
638
661
StringIO = io .StringIO
639
662
BytesIO = io .BytesIO
663
+ del io
640
664
_assertCountEqual = "assertCountEqual"
641
665
if sys .version_info [1 ] <= 1 :
642
666
_assertRaisesRegex = "assertRaisesRegexp"
643
667
_assertRegex = "assertRegexpMatches"
668
+ _assertNotRegex = "assertNotRegexpMatches"
644
669
else :
645
670
_assertRaisesRegex = "assertRaisesRegex"
646
671
_assertRegex = "assertRegex"
672
+ _assertNotRegex = "assertNotRegex"
647
673
else :
648
674
def b (s ):
649
675
return s
@@ -665,6 +691,7 @@ def indexbytes(buf, i):
665
691
_assertCountEqual = "assertItemsEqual"
666
692
_assertRaisesRegex = "assertRaisesRegexp"
667
693
_assertRegex = "assertRegexpMatches"
694
+ _assertNotRegex = "assertNotRegexpMatches"
668
695
_add_doc (b , """Byte literal""" )
669
696
_add_doc (u , """Text literal""" )
670
697
@@ -681,6 +708,10 @@ def assertRegex(self, *args, **kwargs):
681
708
return getattr (self , _assertRegex )(* args , ** kwargs )
682
709
683
710
711
+ def assertNotRegex (self , * args , ** kwargs ):
712
+ return getattr (self , _assertNotRegex )(* args , ** kwargs )
713
+
714
+
684
715
if PY3 :
685
716
exec_ = getattr (moves .builtins , "exec" )
686
717
@@ -716,16 +747,7 @@ def exec_(_code_, _globs_=None, _locs_=None):
716
747
""" )
717
748
718
749
719
- if sys .version_info [:2 ] == (3 , 2 ):
720
- exec_ ("""def raise_from(value, from_value):
721
- try:
722
- if from_value is None:
723
- raise value
724
- raise value from from_value
725
- finally:
726
- value = None
727
- """ )
728
- elif sys .version_info [:2 ] > (3 , 2 ):
750
+ if sys .version_info [:2 ] > (3 ,):
729
751
exec_ ("""def raise_from(value, from_value):
730
752
try:
731
753
raise value from from_value
@@ -805,13 +827,33 @@ def print_(*args, **kwargs):
805
827
_add_doc (reraise , """Reraise an exception.""" )
806
828
807
829
if sys .version_info [0 :2 ] < (3 , 4 ):
830
+ # This does exactly the same what the :func:`py3:functools.update_wrapper`
831
+ # function does on Python versions after 3.2. It sets the ``__wrapped__``
832
+ # attribute on ``wrapper`` object and it doesn't raise an error if any of
833
+ # the attributes mentioned in ``assigned`` and ``updated`` are missing on
834
+ # ``wrapped`` object.
835
+ def _update_wrapper (wrapper , wrapped ,
836
+ assigned = functools .WRAPPER_ASSIGNMENTS ,
837
+ updated = functools .WRAPPER_UPDATES ):
838
+ for attr in assigned :
839
+ try :
840
+ value = getattr (wrapped , attr )
841
+ except AttributeError :
842
+ continue
843
+ else :
844
+ setattr (wrapper , attr , value )
845
+ for attr in updated :
846
+ getattr (wrapper , attr ).update (getattr (wrapped , attr , {}))
847
+ wrapper .__wrapped__ = wrapped
848
+ return wrapper
849
+ _update_wrapper .__doc__ = functools .update_wrapper .__doc__
850
+
808
851
def wraps (wrapped , assigned = functools .WRAPPER_ASSIGNMENTS ,
809
852
updated = functools .WRAPPER_UPDATES ):
810
- def wrapper (f ):
811
- f = functools .wraps (wrapped , assigned , updated )(f )
812
- f .__wrapped__ = wrapped
813
- return f
814
- return wrapper
853
+ return functools .partial (_update_wrapper , wrapped = wrapped ,
854
+ assigned = assigned , updated = updated )
855
+ wraps .__doc__ = functools .wraps .__doc__
856
+
815
857
else :
816
858
wraps = functools .wraps
817
859
@@ -824,7 +866,15 @@ def with_metaclass(meta, *bases):
824
866
class metaclass (type ):
825
867
826
868
def __new__ (cls , name , this_bases , d ):
827
- return meta (name , bases , d )
869
+ if sys .version_info [:2 ] >= (3 , 7 ):
870
+ # This version introduced PEP 560 that requires a bit
871
+ # of extra care (we mimic what is done by __build_class__).
872
+ resolved_bases = types .resolve_bases (bases )
873
+ if resolved_bases is not bases :
874
+ d ['__orig_bases__' ] = bases
875
+ else :
876
+ resolved_bases = bases
877
+ return meta (name , resolved_bases , d )
828
878
829
879
@classmethod
830
880
def __prepare__ (cls , name , this_bases ):
@@ -844,13 +894,75 @@ def wrapper(cls):
844
894
orig_vars .pop (slots_var )
845
895
orig_vars .pop ('__dict__' , None )
846
896
orig_vars .pop ('__weakref__' , None )
897
+ if hasattr (cls , '__qualname__' ):
898
+ orig_vars ['__qualname__' ] = cls .__qualname__
847
899
return metaclass (cls .__name__ , cls .__bases__ , orig_vars )
848
900
return wrapper
849
901
850
902
903
+ def ensure_binary (s , encoding = 'utf-8' , errors = 'strict' ):
904
+ """Coerce **s** to six.binary_type.
905
+
906
+ For Python 2:
907
+ - `unicode` -> encoded to `str`
908
+ - `str` -> `str`
909
+
910
+ For Python 3:
911
+ - `str` -> encoded to `bytes`
912
+ - `bytes` -> `bytes`
913
+ """
914
+ if isinstance (s , binary_type ):
915
+ return s
916
+ if isinstance (s , text_type ):
917
+ return s .encode (encoding , errors )
918
+ raise TypeError ("not expecting type '%s'" % type (s ))
919
+
920
+
921
+ def ensure_str (s , encoding = 'utf-8' , errors = 'strict' ):
922
+ """Coerce *s* to `str`.
923
+
924
+ For Python 2:
925
+ - `unicode` -> encoded to `str`
926
+ - `str` -> `str`
927
+
928
+ For Python 3:
929
+ - `str` -> `str`
930
+ - `bytes` -> decoded to `str`
931
+ """
932
+ # Optimization: Fast return for the common case.
933
+ if type (s ) is str :
934
+ return s
935
+ if PY2 and isinstance (s , text_type ):
936
+ return s .encode (encoding , errors )
937
+ elif PY3 and isinstance (s , binary_type ):
938
+ return s .decode (encoding , errors )
939
+ elif not isinstance (s , (text_type , binary_type )):
940
+ raise TypeError ("not expecting type '%s'" % type (s ))
941
+ return s
942
+
943
+
944
+ def ensure_text (s , encoding = 'utf-8' , errors = 'strict' ):
945
+ """Coerce *s* to six.text_type.
946
+
947
+ For Python 2:
948
+ - `unicode` -> `unicode`
949
+ - `str` -> `unicode`
950
+
951
+ For Python 3:
952
+ - `str` -> `str`
953
+ - `bytes` -> decoded to `str`
954
+ """
955
+ if isinstance (s , binary_type ):
956
+ return s .decode (encoding , errors )
957
+ elif isinstance (s , text_type ):
958
+ return s
959
+ else :
960
+ raise TypeError ("not expecting type '%s'" % type (s ))
961
+
962
+
851
963
def python_2_unicode_compatible (klass ):
852
964
"""
853
- A decorator that defines __unicode__ and __str__ methods under Python 2.
965
+ A class decorator that defines __unicode__ and __str__ methods under Python 2.
854
966
Under Python 3 it does nothing.
855
967
856
968
To support Python 2 and 3 with a single code base, define a __str__ method
0 commit comments