Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fd71bcb

Browse files
committedNov 18, 2024·
refactor: Remove aliases for str or map
1 parent cfb72c7 commit fd71bcb

File tree

2 files changed

+22
-26
lines changed

2 files changed

+22
-26
lines changed
 

‎bottle.py

+20-24
Original file line numberDiff line numberDiff line change
@@ -105,12 +105,8 @@ def getargspec(func):
105105
kwargs = makelist(spec[0]) + makelist(spec.kwonlyargs)
106106
return kwargs, spec[1], spec[2], spec[3]
107107

108-
basestring = str
109-
unicode = str
110108
json_loads = lambda s: json_lds(touni(s))
111109
callable = lambda x: hasattr(x, '__call__')
112-
imap = map
113-
114110

115111
def _wsgi_recode(src):
116112
""" Translate a PEP-3333 latin1-string to utf8+surrogateescape """
@@ -125,7 +121,7 @@ def _raise(*a):
125121

126122
# Some helpers for string/byte handling
127123
def tob(s, enc='utf8'):
128-
if isinstance(s, unicode):
124+
if isinstance(s, str):
129125
return s.encode(enc)
130126
return b'' if s is None else bytes(s)
131127

@@ -878,7 +874,7 @@ def hello(name):
878874
skiplist = makelist(skip)
879875

880876
def decorator(callback):
881-
if isinstance(callback, basestring): callback = load(callback)
877+
if isinstance(callback, str): callback = load(callback)
882878
for rule in makelist(path) or yieldroutes(callback):
883879
for verb in makelist(method):
884880
verb = verb.upper()
@@ -927,7 +923,7 @@ def error_handler_404(error):
927923
"""
928924

929925
def decorator(callback):
930-
if isinstance(callback, basestring): callback = load(callback)
926+
if isinstance(callback, str): callback = load(callback)
931927
self.error_handler[int(code)] = callback
932928
return callback
933929

@@ -979,8 +975,8 @@ def _handle(self, environ):
979975
def _cast(self, out, peek=None):
980976
""" Try to convert the parameter into something WSGI compatible and set
981977
correct HTTP headers when possible.
982-
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
983-
iterable of strings and iterable of unicodes
978+
Support: False, bytes/bytearray, str, dict, HTTPResponse, HTTPError, file-like,
979+
iterable of bytes/bytearray or str instances.
984980
"""
985981

986982
# Empty output is done here
@@ -990,10 +986,10 @@ def _cast(self, out, peek=None):
990986
return []
991987
# Join lists of byte or unicode strings. Mixed lists are NOT supported
992988
if isinstance(out, (tuple, list))\
993-
and isinstance(out[0], (bytes, unicode)):
989+
and isinstance(out[0], (bytes, str)):
994990
out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
995991
# Encode unicode strings
996-
if isinstance(out, unicode):
992+
if isinstance(out, str):
997993
out = out.encode(response.charset)
998994
# Byte Strings are just returned
999995
if isinstance(out, bytes):
@@ -1039,9 +1035,9 @@ def _cast(self, out, peek=None):
10391035
return self._cast(first)
10401036
elif isinstance(first, bytes):
10411037
new_iter = itertools.chain([first], iout)
1042-
elif isinstance(first, unicode):
1038+
elif isinstance(first, str):
10431039
encoder = lambda x: x.encode(response.charset)
1044-
new_iter = imap(encoder, itertools.chain([first], iout))
1040+
new_iter = map(encoder, itertools.chain([first], iout))
10451041
else:
10461042
msg = 'Unsupported response type: %s' % type(first)
10471043
return self._cast(HTTPError(500, msg))
@@ -1809,15 +1805,15 @@ def set_cookie(self, name, value, secret=None, digestmod=hashlib.sha256, **optio
18091805
Morsel._reserved.setdefault('samesite', 'SameSite')
18101806

18111807
if secret:
1812-
if not isinstance(value, basestring):
1808+
if not isinstance(value, str):
18131809
depr(0, 13, "Pickling of arbitrary objects into cookies is "
18141810
"deprecated.", "Only store strings in cookies. "
18151811
"JSON strings are fine, too.")
18161812
encoded = base64.b64encode(pickle.dumps([name, value], -1))
18171813
sig = base64.b64encode(hmac.new(tob(secret), encoded,
18181814
digestmod=digestmod).digest())
18191815
value = touni(b'!' + sig + b'?' + encoded)
1820-
elif not isinstance(value, basestring):
1816+
elif not isinstance(value, str):
18211817
raise TypeError('Secret key required for non-string cookies.')
18221818

18231819
# Cookie size plus options must not exceed 4kb.
@@ -2157,7 +2153,7 @@ def getunicode(self, name, default=None, encoding=None):
21572153
""" (deprecated) Return the value as a unicode string, or the default. """
21582154
return self.get(name, default)
21592155

2160-
def __getattr__(self, name, default=unicode()):
2156+
def __getattr__(self, name, default=str()):
21612157
# Without this guard, pickle generates a cryptic TypeError:
21622158
if name.startswith('__') and name.endswith('__'):
21632159
return super(FormsDict, self).__getattr__(name)
@@ -2326,7 +2322,7 @@ def load_dict(self, source, namespace=''):
23262322
{'some.namespace.key': 'value'}
23272323
"""
23282324
for key, value in source.items():
2329-
if isinstance(key, basestring):
2325+
if isinstance(key, str):
23302326
nskey = (namespace + '.' + key).strip('.')
23312327
if isinstance(value, dict):
23322328
self.load_dict(value, namespace=nskey)
@@ -2344,7 +2340,7 @@ def update(self, *a, **ka):
23442340
>>> c.update('some.namespace', key='value')
23452341
"""
23462342
prefix = ''
2347-
if a and isinstance(a[0], basestring):
2343+
if a and isinstance(a[0], str):
23482344
prefix = a[0].strip('.') + '.'
23492345
a = a[1:]
23502346
for key, value in dict(*a, **ka).items():
@@ -2356,7 +2352,7 @@ def setdefault(self, key, value=None):
23562352
return self[key]
23572353

23582354
def __setitem__(self, key, value):
2359-
if not isinstance(key, basestring):
2355+
if not isinstance(key, str):
23602356
raise TypeError('Key has type %r (not a string)' % type(key))
23612357

23622358
self._virtual_keys.discard(key)
@@ -2681,7 +2677,7 @@ def save(self, destination, overwrite=False, chunk_size=2 ** 16):
26812677
:param overwrite: If True, replace existing files. (default: False)
26822678
:param chunk_size: Bytes to read at a time. (default: 64kb)
26832679
"""
2684-
if isinstance(destination, basestring): # Except file-likes here
2680+
if isinstance(destination, str): # Except file-likes here
26852681
if os.path.isdir(destination):
26862682
destination = os.path.join(destination, self.filename)
26872683
if not overwrite and os.path.exists(destination):
@@ -2847,7 +2843,7 @@ def debug(mode=True):
28472843

28482844

28492845
def http_date(value):
2850-
if isinstance(value, basestring):
2846+
if isinstance(value, str):
28512847
return value
28522848
if isinstance(value, datetime):
28532849
# aware datetime.datetime is converted to UTC time
@@ -3836,13 +3832,13 @@ def run(app=None,
38363832
try:
38373833
if debug is not None: _debug(debug)
38383834
app = app or default_app()
3839-
if isinstance(app, basestring):
3835+
if isinstance(app, str):
38403836
app = load_app(app)
38413837
if not callable(app):
38423838
raise ValueError("Application is not callable: %r" % app)
38433839

38443840
for plugin in plugins or []:
3845-
if isinstance(plugin, basestring):
3841+
if isinstance(plugin, str):
38463842
plugin = load(plugin)
38473843
app.install(plugin)
38483844

@@ -3851,7 +3847,7 @@ def run(app=None,
38513847

38523848
if server in server_names:
38533849
server = server_names.get(server)
3854-
if isinstance(server, basestring):
3850+
if isinstance(server, str):
38553851
server = load(server)
38563852
if isinstance(server, type):
38573853
server = server(host=host, port=port, **kargs)

‎test/tools.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import mimetypes
1414
import uuid
1515

16-
from bottle import tob, BytesIO, unicode
16+
from bottle import tob, BytesIO
1717

1818

1919
def warn(msg):
@@ -167,7 +167,7 @@ def multipart_environ(fields, files):
167167
body += 'Content-Type: %s\r\n\r\n' % mimetype
168168
body += content + '\r\n'
169169
body += boundary + '--\r\n'
170-
if isinstance(body, unicode):
170+
if isinstance(body, str):
171171
body = body.encode('utf8')
172172
env['CONTENT_LENGTH'] = str(len(body))
173173
env['wsgi.input'].write(body)

0 commit comments

Comments
 (0)
Please sign in to comment.