Here are the examples of the python api sys.getdefaultencoding taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
101 Examples
5
Example 1
def test_resetmethod(self):
gde = sys.getdefaultencoding
sys.getdefaultencoding = 5
self.assertEquals(sys.getdefaultencoding, 5)
del sys.getdefaultencoding
self.assertRaises(AttributeError, getattr, sys, 'getdefaultencoding')
sys.getdefaultencoding = gde
3
Example 2
Project: scikit-image Source File: _build.py
def process_tempita_pyx(fromfile):
try:
try:
from Cython import Tempita as tempita
except ImportError:
import tempita
except ImportError:
raise Exception('Building requires Tempita: '
'pip install --user Tempita')
template = tempita.Template.from_filename(fromfile,
encoding=sys.getdefaultencoding())
pyxcontent = template.substitute()
if not fromfile.endswith('.pyx.in'):
raise ValueError("Unexpected extension of %s." % fromfile)
pyxfile = os.path.splitext(fromfile)[0] # split off the .in ending
with open(pyxfile, "w") as f:
f.write(pyxcontent)
3
Example 3
@staticmethod
def print_dict(data={}, key='', prefix=''):
try:
if isinstance(data, dict):
for key in data:
Debug.print_dict(data[key], key, prefix + ' ')
else:
if isinstance(data, basestring):
print prefix + unicode(key) + ' => ' + data
else:
print prefix + unicode(key) + ' => ' + unicode(data)
except UnicodeEncodeError as error:
Debug.logger.info(u'编码异常')
Debug.logger.info(u'系统默认编码为:' + sys.getdefaultencoding())
raise error
return
3
Example 4
def _getNameString(self, codec=None):
if codec is None:
codec = sys.getdefaultencoding()
name = None
# try to find name
if 'name' in self.fields:
name = self.fields['name']
# if name is unicode, try to decode
if isinstance(name, unicode):
try:
name = name.encode(codec)
except UnicodeError:
name = None
return name
3
Example 5
Project: xunlei-lixian Source File: diagnostics.py
@command(name='diagnostics', usage='print helpful information for diagnostics')
def lx_diagnostics(args):
'''
usage: lx diagnostics
'''
from lixian_encoding import default_encoding
print 'default_encoding ->', default_encoding
import sys
print 'sys.getdefaultencoding() ->', sys.getdefaultencoding()
print 'sys.getfilesystemencoding() ->', sys.getfilesystemencoding()
print r"print u'\u4e2d\u6587'.encode('utf-8') ->", u'\u4e2d\u6587'.encode('utf-8')
print r"print u'\u4e2d\u6587'.encode('gbk') ->", u'\u4e2d\u6587'.encode('gbk')
3
Example 6
def u(text):
if text is None:
return None
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
try:
return unicode(text)
except:
return text.decode('utf-8', 'replace')
3
Example 7
def _parseString(self):
# Strings are null-terminated
count = 0
while self.data[self.offset + count ] != 0:
count += 1
value = self.data[self.offset:self.offset + count].decode(sys.getdefaultencoding(), 'replace')
self.offset += count + 1
return value
3
Example 8
def __call__(self, environ, start_response):
def to_native(x, charset=sys.getdefaultencoding(), errors='strict'):
if x is None or isinstance(x, str):
return x
return x.decode(charset, errors)
def fix_headers(status, headers, exc_info=None):
headers = [(to_native(key), value) for key, value in headers]
return start_response(status, headers, exc_info)
return self.app(environ, fix_headers)
3
Example 9
Project: iris Source File: test_cdm.py
@contextmanager
def unicode_encoding_change(self, new_encoding):
default_encoding = sys.getdefaultencoding()
reload(sys).setdefaultencoding(new_encoding)
yield
sys.setdefaultencoding(default_encoding)
del sys.setdefaultencoding
3
Example 10
Project: yadapy Source File: local.py
def sysexec(self, *argv, **popen_opts):
""" return stdout text from executing a system child process,
where the 'self' path points to executable.
The process is directly invoked and not through a system shell.
"""
from subprocess import Popen, PIPE
argv = map_as_list(str, argv)
popen_opts['stdout'] = popen_opts['stderr'] = PIPE
proc = Popen([str(self)] + argv, **popen_opts)
stdout, stderr = proc.communicate()
ret = proc.wait()
if py.builtin._isbytes(stdout):
stdout = py.builtin._totext(stdout, sys.getdefaultencoding())
if ret != 0:
if py.builtin._isbytes(stderr):
stderr = py.builtin._totext(stderr, sys.getdefaultencoding())
raise py.process.cmdexec.Error(ret, ret, str(self),
stdout, stderr,)
return stdout
3
Example 11
Project: dask Source File: csv.py
@delayed
def _to_csv_chunk(df, **kwargs):
import io
if PY2:
out = io.BytesIO()
else:
out = io.StringIO()
df.to_csv(out, **kwargs)
out.seek(0)
if PY2:
return out.getvalue()
encoding = kwargs.get('encoding', sys.getdefaultencoding())
return out.getvalue().encode(encoding)
3
Example 12
def __init__(self, multi=None, encoding=None, errors='strict',
decode_keys=False):
self.multi = multi
if encoding is None:
encoding = sys.getdefaultencoding()
self.encoding = encoding
self.errors = errors
self.decode_keys = decode_keys
3
Example 13
def prints(tstr):
""" lovely unicode
"""
sys.stdout.write('%s\n' % (tstr.encode(sys.getdefaultencoding(),
'replace')))
sys.stdout.flush()
3
Example 14
def u(text):
if text is None:
return None
if isinstance(text, bytes):
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
pass
try:
return str(text)
except:
return text
3
Example 15
def __init__(self, root, **kw):
"""Just set the root and any other attribs passes via **kw."""
self.root = root
self.encoding = sys.getdefaultencoding()
for k, v in kw.items():
setattr(self, k, v)
3
Example 16
Project: lino Source File: __init__.py
def unicode_string(x):
"""
When we want unicode strings (e.g. translated exception messages)
to appear in an Exception,
we must first encode them using a non-strict errorhandler.
Because the message of an Exception may not be a unicode string.
"""
return str(x).encode(sys.getdefaultencoding(), 'backslashreplace')
3
Example 17
Project: spitfire Source File: i18n.py
def macro_i18n(macro_node, arg_map, compiler):
# fixme: parse the parameter list into something usable
# macro_node.parameter_list
# generate a fake translation for now to verify this is working
# most apps will have to stub this part out somehow i think
macro_content_ast = util.parse(macro_node.value, 'i18n_goal')
i18n_msg = make_i18n_message(macro_node.value, macro_content_ast)
i18n_msg_utf8 = i18n_msg.encode(sys.getdefaultencoding())
#print "macro_content_ast"
#print "orginal:", macro_node.value
#print "i18n:", i18n_msg_utf8
#visitor.print_tree(macro_content_ast)
return i18n_msg
3
Example 18
Project: megaman Source File: cythonize.py
def process_tempita_pyx(fromfile, tofile):
try:
try:
from Cython import Tempita as tempita
except ImportError:
import tempita
except ImportError:
raise Exception('Building megaman requires Tempita: '
'pip install --user Tempita')
from_filename = tempita.Template.from_filename
template = from_filename(fromfile, encoding=sys.getdefaultencoding())
pyxcontent = template.substitute()
assert fromfile.endswith('.pyx.in')
pyxfile = fromfile[:-len('.pyx.in')] + '.pyx'
with open(pyxfile, "w") as f:
f.write(pyxcontent)
process_pyx(pyxfile, tofile)
3
Example 19
def _get_name_string(self, codec=None):
"""Get the name"""
if codec is None:
codec = sys.getdefaultencoding()
name = None
# try to find name
if 'name' in self._fields:
name = self._fields['name'].value
# if name is unicode, try to decode
if isinstance(name, text_type):
try:
name = name.encode(codec)
except UnicodeError:
name = None
return name
3
Example 20
Project: simple-monitor-alert Source File: sensors.py
def get_sensors():
chips = []
chip = None
sensor = None
for line in check_output(['sensors', '-u', '--no-adapter']).split(b'\n'):
line = line.decode(sys.getdefaultencoding())
line = line.rstrip('\n')
if not line:
chip = None
elif chip is None:
chip = Chip(line)
chips.append(chip)
elif not line.startswith(' '):
sensor = Sensor(line)
chip.append(sensor)
else:
sensor.add_line(line)
return chips
3
Example 21
Project: typefacet Source File: test_renderer.py
def test_string_encoding__default(self):
"""
Check the default value.
"""
renderer = Renderer()
self.assertEqual(renderer.string_encoding, sys.getdefaultencoding())
3
Example 22
def init(self, filename, mode="r", bufsize=BUFSIZE, encoding=None,
channel=channel):
self._mode = mode
self._bufsize = bufsize
self._filename = filename
self._encoding = encoding or getdefaultencoding()
self._fd = None
self._poller = None
self._buffer = deque()
self._closeflag = False
3
Example 23
Project: pyexcel Source File: sheet.py
def __repr__(self):
if compact.PY2:
default_encoding = sys.getdefaultencoding()
if default_encoding == "ascii":
result = self.texttable
return result.encode('utf-8')
return self.texttable
3
Example 24
Project: odoo-development Source File: dev_code_tester.py
def _begin_execute(self):
""" Switch encoding to UTF-8 and capture stdout to an StringIO object
:return: current captured sys.stdout
"""
new_stdout = StringIO()
self._encoding = sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf-8')
self._stdout = sys.stdout
sys.stdout = new_stdout
return new_stdout
3
Example 25
@classmethod
def _decode_page(cls, page):
"""Read the encoding (charset) of ``page`` and try to encode it using
UTF-8."""
contents = page.read()
encoding = cls._get_encoding(page, contents) or sys.getdefaultencoding()
return unicode(contents, encoding=encoding).encode('utf-8')
3
Example 26
def output_result(result, hide_empty=False):
output = result['output']
if result['returncode'] == NotImplemented:
output = ansi('yellowf') + output + ansi('reset')
elif result['returncode']:
if not output:
output = 'Failed with return code %d' % result['returncode']
output = ansi('redf') + output + ansi('reset')
elif not result['cmd']:
output = ansi('yellowf') + output + ansi('reset')
if output or not hide_empty:
client = result['client']
print(ansi('bluef') + '=== ' + ansi('boldon') + client.path + ansi('boldoff') + ' (' + client.__class__.type + ') ===' + ansi('reset'))
if output:
try:
print(output)
except UnicodeEncodeError:
print(output.encode(sys.getdefaultencoding(), 'replace'))
3
Example 27
Project: ispyd Source File: python.py
def do_defaultencoding(self, line):
"""defaultencoding
Display the default encoding used when converting Unicode strings.
This is the value available from 'sys.defaultencoding'."""
print >> self.stdout, sys.getdefaultencoding()
3
Example 28
Project: web Source File: fetch_blacklist.py
def printE(self, msg, newline=True):
"""Print to stderr. This expects unicode strings!"""
encoding = self.stderr.encoding or sys.getdefaultencoding()
self.stderr.write(msg.encode(encoding, 'replace'))
if newline:
self.stdout.write('\n')
3
Example 29
Project: py12306 Source File: winmanifest.py
def parse(self, filename_or_file, initialize=True):
""" Load manifest from file or file object """
if isinstance(filename_or_file, (str, unicode)):
filename = filename_or_file
else:
filename = filename_or_file.name
try:
domtree = minidom.parse(filename_or_file)
except xml.parsers.expat.ExpatError, e:
args = [e.args[0]]
if isinstance(filename, unicode):
filename = filename.encode(sys.getdefaultencoding(), "replace")
args.insert(0, '\n File "%s"\n ' % filename)
raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
if initialize:
self.__init__()
self.filename = filename
self.load_dom(domtree, False)
3
Example 30
Project: PyFunt Source File: cythonize.py
def process_tempita_pyx(fromfile, tofile):
try:
try:
from Cython import Tempita as tempita
except ImportError:
import tempita
except ImportError:
raise Exception('Building PyFunt requires Tempita: '
'pip install --user Tempita')
from_filename = tempita.Template.from_filename
template = from_filename(fromfile, encoding=sys.getdefaultencoding())
pyxcontent = template.substitute()
assert fromfile.endswith('.pyx.in')
pyxfile = fromfile[:-len('.pyx.in')] + '.pyx'
with open(pyxfile, "w") as f:
f.write(pyxcontent)
process_pyx(pyxfile, tofile)
3
Example 31
def serialize(layout):
def _ser(widget, element):
if isinstance(widget, SERIALIZABLE):
sub = SubElement(element, type(widget).__name__.lower() , attributes(widget))
widget.foreach(_ser, sub)
else:
sub = SubElement(element, 'widget', attributes(widget))
tree = Element('layout')
map(_ser, layout.frames, [tree] * len(layout.frames))
return tostring(tree, encoding=sys.getdefaultencoding())
3
Example 32
def u(text):
if text is None:
return None
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
try:
return unicode(text)
except:
return text
3
Example 33
Project: KeenClient-Python Source File: client.py
def generate_image_beacon(self, event_collection, event_body, timestamp=None):
""" Generates an image beacon URL.
:param event_collection: the name of the collection to insert the
event to
:param event_body: dict, the body of the event to insert the event to
:param timestamp: datetime, optional, the timestamp of the event
"""
event = Event(self.project_id, event_collection, event_body,
timestamp=timestamp)
event_json = event.to_json()
return "{0}/{1}/projects/{2}/events/{3}?api_key={4}&data={5}".format(
self.api.base_url, self.api.api_version, self.project_id, self._url_escape(event_collection),
self.api.write_key.decode(sys.getdefaultencoding()), self._base64_encode(event_json)
)
3
Example 34
Project: pyblish-base Source File: _compat.py
def get_best_encoding(stream):
"""Returns the default stream encoding if not found."""
rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv
3
Example 35
Project: pgi Source File: test_misc.py
def test_module_dir(self):
# make sure all descriptors show up in dir(module)
self.assertTrue(len(dir(Gtk)) > 750)
if _compat.PY2:
self.assertEqual(sys.getdefaultencoding(), "ascii")
else:
self.assertEqual(sys.getdefaultencoding(), "utf-8")
self.assertEqual(Gtk._version, "3.0")
self.assertEqual(GObject._version, "2.0")
self.assertEqual(GLib._version, "2.0")
3
Example 36
def u(text):
if text is None:
return None
if isinstance(text, bytes):
try:
return text.decode('utf-8')
except:
try:
return text.decode(sys.getdefaultencoding())
except:
pass
try:
return str(text)
except:
return text.decode('utf-8', 'replace')
3
Example 37
def open(self):
if self._ds: return
self._ds = libgdal.OGROpen(self.datasource.encode(sys.getdefaultencoding()), False, None)
if self._ds is None:
msg = None
if libgdal.CPLGetLastErrorMsg:
msg = libgdal.CPLGetLastErrorMsg()
if not msg:
msg = 'failed to open %s' % self.datasource
raise OGRShapeReaderError(msg)
3
Example 38
@classmethod
def set_cwd(cls, cwd):
"""
Set the cwd that is used to manipulate paths.
"""
if isinstance(cwd, six.binary_type):
cwd = cwd.decode(sys.getdefaultencoding())
cls._cwd = cwd
cls._root = cls._git_root()
3
Example 39
Project: python-unio Source File: unio.py
def get_std_stream_encoding():
"""Returns the default stream encoding if not found."""
rv = sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv
3
Example 40
Project: pylint Source File: spelling.py
def _check_docstring(self, node):
"""check the node has any spelling errors"""
docstring = node.doc
if not docstring:
return
start_line = node.lineno + 1
if six.PY2:
encoding = node.root().file_encoding
docstring = docstring.decode(encoding or sys.getdefaultencoding(),
'replace')
# Go through lines of docstring
for idx, line in enumerate(docstring.splitlines()):
self._check_spelling('wrong-spelling-in-docstring',
line, start_line + idx)
3
Example 41
Project: AWS-Lambda-ML-Microservice-Skeleton Source File: test_mio5_utils.py
def _make_readerlike(stream, byte_order=boc.native_code):
class R(object):
pass
r = R()
r.mat_stream = stream
r.byte_order = byte_order
r.struct_as_record = True
r.uint16_codec = sys.getdefaultencoding()
r.chars_as_strings = False
r.mat_dtype = False
r.squeeze_me = False
return r
3
Example 42
def decode(s):
"""
Decode a string using the system encoding if needed (ie byte strings)
"""
if isinstance(s, bytes):
return s.decode(sys.getdefaultencoding())
else:
return s
3
Example 43
def process_tempita_pyx(fromfile, tofile):
try:
try:
from Cython import Tempita as tempita
except ImportError:
import tempita
except ImportError:
raise Exception('Building SciPy requires Tempita: '
'pip install --user Tempita')
from_filename = tempita.Template.from_filename
template = from_filename(fromfile, encoding=sys.getdefaultencoding())
pyxcontent = template.substitute()
assert fromfile.endswith('.pyx.in')
pyxfile = fromfile[:-len('.pyx.in')] + '.pyx'
with open(pyxfile, "w") as f:
f.write(pyxcontent)
process_pyx(pyxfile, tofile)
3
Example 44
def decode(self, byte_string, encoding=None, errors='strict'):
if not isinstance(byte_string, str):
raise VumiCodecException(
'Only bytestrings accepted for decoding.')
encoding = encoding or sys.getdefaultencoding()
if encoding in self.custom_codecs:
decoder = self.custom_codecs[encoding].decode
else:
decoder = codecs.getdecoder(encoding)
obj, length = decoder(byte_string, errors)
return obj
3
Example 45
def __init__(self, multi, encoding=None, errors='strict',
decode_keys=False):
self.multi = multi
if encoding is None:
encoding = sys.getdefaultencoding()
self.encoding = encoding
self.errors = errors
self.decode_keys = decode_keys
3
Example 46
def binary(string, var=None):
"""Makes ``string`` to :class:`str` in Python 2.
Makes ``string`` to :class:`bytes` in Python 3 or IronPython.
:param string: a string to cast it to :data:`binary_type`
:type string: :class:`bytes`, :class:`str`, :class:`unicode`
:param var: an optional variable name to be used for error message
:type var: :class:`str`
"""
if isinstance(string, text_type):
if IRON_PYTHON:
return bytes(string, sys.getdefaultencoding())
return string.encode()
elif isinstance(string, binary_type):
return string
if var:
raise TypeError('{0} must be a string, not {1!r}'.format(var, string))
raise TypeError('expected a string, not ' + repr(string))
2
Example 47
Project: mako Source File: test_exceptions.py
@requires_pygments_14
def test_utf8_html_error_template_pygments(self):
"""test the html_error_template with a Template containing UTF-8
chars"""
if compat.py3k:
code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${'привет'}
% endif
"""
else:
code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${u'привет'}
% endif
"""
try:
template = Template(code)
template.render_unicode()
except exceptions.CompileException:
html_error = exceptions.html_error_template().render()
if compat.py3k:
assert ("CompileException: Fragment 'if 2 == 2: /an "
"error' is not a partial control statement "
"at line: 2 char: 1").encode(sys.getdefaultencoding(), 'htmlentityreplace') in \
html_error
else:
assert ("CompileException: Fragment 'if 2 == 2: /an "
"error' is not a partial control statement "
"at line: 2 char: 1") in \
html_error
if compat.py3k:
assert "".encode(sys.getdefaultencoding(),
'htmlentityreplace') in html_error
else:
assert 'u''\
'привет'\
''</span><span class="cp">}</span>'.encode(
sys.getdefaultencoding(),
'htmlentityreplace') in html_error
else:
assert False, ("This function should trigger a CompileException, "
"but didn't")
2
Example 48
Project: mako Source File: test_exceptions.py
@requires_no_pygments_exceptions
def test_utf8_html_error_template_no_pygments(self):
"""test the html_error_template with a Template containing UTF-8
chars"""
if compat.py3k:
code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${'привет'}
% endif
"""
else:
code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${u'привет'}
% endif
"""
try:
template = Template(code)
template.render_unicode()
except exceptions.CompileException:
html_error = exceptions.html_error_template().render()
if compat.py3k:
assert ("CompileException: Fragment 'if 2 == 2: /an "
"error' is not a partial control statement "
"at line: 2 char: 1").encode(sys.getdefaultencoding(),
'htmlentityreplace') in \
html_error
else:
assert ("CompileException: Fragment 'if 2 == 2: /an "
"error' is not a partial control statement "
"at line: 2 char: 1") in \
html_error
if compat.py3k:
assert "${'привет'}".encode(sys.getdefaultencoding(),
'htmlentityreplace') in html_error
else:
assert u("${u'привет'}").encode(sys.getdefaultencoding(),
'htmlentityreplace') in html_error
else:
assert False, ("This function should trigger a CompileException, "
"but didn't")
2
Example 49
Project: pykickstart Source File: parser.py
def _preprocessStateMachine(lineIter):
l = None
lineno = 0
retval = ""
if six.PY3:
retval = retval.encode(sys.getdefaultencoding())
while True:
try:
l = next(lineIter)
except StopIteration:
break
# At the end of the file?
if l == "":
break
lineno += 1
ksurl = None
ll = l.strip()
if not ll.startswith("%ksappend"):
if six.PY3:
l = l.encode(sys.getdefaultencoding())
retval += l
continue
# Try to pull down the remote file.
try:
ksurl = ll.split(' ')[1]
except:
raise KickstartParseError(formatErrorMsg(lineno, msg=_("Illegal url for %%ksappend: %s") % ll))
try:
contents = load_to_str(ksurl)
except KickstartError as e:
raise KickstartError(formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file: %s") % str(e)))
# If that worked, write the remote file to the output kickstart
# file in one burst. This allows multiple %ksappend lines to
# exist.
if contents is not None:
retval += contents.encode(sys.getdefaultencoding())
return retval
0
Example 50
def getcallargs(func, *positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
args, varargs, varkw, defaults = getargspec(func)
f_name = func.__name__
arg2value = {}
# The following closures are basically because of tuple parameter unpacking.
assigned_tuple_params = []
def assign(arg, value):
if isinstance(arg, str):
arg2value[arg] = value
else:
assigned_tuple_params.append(arg)
value = iter(value)
for i, subarg in enumerate(arg):
try:
subvalue = next(value)
except StopIteration:
raise ValueError('need more than %d %s to unpack' %
(i, 'values' if i > 1 else 'value'))
assign(subarg,subvalue)
try:
next(value)
except StopIteration:
pass
else:
raise ValueError('too many values to unpack')
def is_assigned(arg):
if isinstance(arg,str):
return arg in arg2value
return arg in assigned_tuple_params
if ismethod(func) and func.im_self is not None:
# implicit 'self' (or 'cls' for classmethods) argument
positional = (func.im_self,) + positional
num_pos = len(positional)
num_total = num_pos + len(named)
num_args = len(args)
num_defaults = len(defaults) if defaults else 0
for arg, value in zip(args, positional):
assign(arg, value)
if varargs:
if num_pos > num_args:
assign(varargs, positional[-(num_pos-num_args):])
else:
assign(varargs, ())
elif 0 < num_args < num_pos:
raise TypeError('%s() takes %s %d %s (%d given)' % (
f_name, 'at most' if defaults else 'exactly', num_args,
'arguments' if num_args > 1 else 'argument', num_total))
elif num_args == 0 and num_total:
if varkw:
if num_pos:
# XXX: We should use num_pos, but Python also uses num_total:
raise TypeError('%s() takes exactly 0 arguments '
'(%d given)' % (f_name, num_total))
else:
raise TypeError('%s() takes no arguments (%d given)' %
(f_name, num_total))
for arg in args:
if isinstance(arg, str) and arg in named:
if is_assigned(arg):
raise TypeError("%s() got multiple values for keyword "
"argument '%s'" % (f_name, arg))
else:
assign(arg, named.pop(arg))
if defaults: # fill in any missing values with the defaults
for arg, value in zip(args[-num_defaults:], defaults):
if not is_assigned(arg):
assign(arg, value)
if varkw:
assign(varkw, named)
elif named:
unexpected = next(iter(named))
try:
unicode
except NameError:
pass
else:
if isinstance(unexpected, unicode):
unexpected = unexpected.encode(sys.getdefaultencoding(), 'replace')
raise TypeError("%s() got an unexpected keyword argument '%s'" %
(f_name, unexpected))
unassigned = num_args - len([arg for arg in args if is_assigned(arg)])
if unassigned:
num_required = num_args - num_defaults
raise TypeError('%s() takes %s %d %s (%d given)' % (
f_name, 'at least' if defaults else 'exactly', num_required,
'arguments' if num_required > 1 else 'argument', num_total))
return arg2value