text
stringlengths
81
112k
Gets rid of the used parts of the buffer. def _consume(self): """ Gets rid of the used parts of the buffer. """ self._stream_offset += self._buff_i - self._buf_checkpoint self._buf_checkpoint = self._buff_i
Establish a socket connection and set nodelay settings on it. :return: New socket connection. def _new_conn(self): """ Establish a socket connection and set nodelay settings on it. :return: New socket connection. """ extra_kw = {} if self.source_address: ex...
Alternative to the common request method, which sends the body with chunked encoding and not as one block def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block ...
This method should only be called once, before the connection is used. def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None): """ This method should only be cal...
Catch known errors and prettify them instead of showing the entire traceback, for better UX def prettify_exc(error): """Catch known errors and prettify them instead of showing the entire traceback, for better UX""" matched_exceptions = [k for k in KNOWN_EXCEPTIONS.keys() if k in error] if not match...
Get the OS appropriate handle for the corresponding output stream. :param str stream: The the stream to get the handle for :return: A handle to the appropriate stream, either a ctypes buffer or **sys.stdout** or **sys.stderr**. def get_stream_handle(stream=sys.stdout): """ Get the OS appr...
Hide the console cursor on the given stream :param stream: The name of the stream to get the handle for :return: None :rtype: None def hide_cursor(stream=sys.stdout): """ Hide the console cursor on the given stream :param stream: The name of the stream to get the handle for :return: None ...
Returns the completion results for click.core.Choice Parameters ---------- ctx : click.core.Context The current context incomplete : The string to complete Returns ------- [(str, str)] A list of completion results def choice_complete(self, ctx, incomplete): """...
Internal handler for the bash completion support. Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line complete_var : str The environment variable name used to control the completion behavior (De...
Patch click def patch(): """Patch click""" import click click.types.ParamType.complete = param_type_complete click.types.Choice.complete = choice_complete click.core.MultiCommand.get_command_short_help = multicommand_get_command_short_help click.core._bashcomplete = _shellcomplete
expr ::= seq ( '|' seq )* ; def parse_expr(tokens, options): """expr ::= seq ( '|' seq )* ;""" seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_...
seq ::= ( atom [ '...' ] )* ; def parse_seq(tokens, options): """seq ::= ( atom [ '...' ] )* ;""" result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move()...
Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; def parse_argv(tokens, options, options_first=False): """Parse command-line argument vector. I...
Flatten an arbitrarily nested iterable :param elem: An iterable to flatten :type elem: :class:`~collections.Iterable` >>> nested_iterable = (1234, (3456, 4398345, (234234)), (2396, (23895750, 9283798, 29384, (289375983275, 293759, 2347, (2098, 7987, 27599))))) >>> list(vistir.misc.unnest(nested_iterab...
Use `subprocess.Popen` to get the output of a command and decode it. :param list cmd: A list representing the command you want to run. :param dict env: Additional environment settings to pass through to the subprocess. :param bool return_object: When True, returns the whole subprocess instance :param b...
Load the :mod:`sys.path` from the given python executable's environment as json :param str python: Path to a valid python executable :return: A python representation of the `sys.path` value of the given python executable. :rtype: list >>> load_path("/home/user/.virtualenvs/requirementslib-5MhGuG3C/bin...
Force a value to bytes. :param string: Some input that can be converted to a bytes. :type string: str or bytes unicode or a memoryview subclass :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: Corresponding byte representation (for us...
Force a value to a text-type. :param string: Some input that can be converted to a unicode representation. :type string: str or bytes unicode :param encoding: The encoding to use for conversions, defaults to "utf-8" :param encoding: str, optional :return: The unicode representation of the string ...
split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping :param int n: Number of unique groups :param iter iterable: An iterable to split up :return: a list of new iterables derived from the original iterable :rtype: list def divide(n, iterable): """ ...
Determine the proper output encoding for terminal rendering def getpreferredencoding(): """Determine the proper output encoding for terminal rendering""" # Borrowed from Invoke # (see https://github.com/pyinvoke/invoke/blob/93af29d/invoke/runners.py#L881) _encoding = locale.getpreferredencoding(False)...
Given a string, decode it for output to a terminal :param str output: A string to print to a terminal :param target_stream: A stream to write to, we will encode to target this stream if possible. :param dict translation_map: A mapping of unicode character ordinals to replacement strings. :return: A re-...
Given an encoding name, get the canonical name from a codec lookup. :param str name: The name of the codec to lookup :return: The canonical version of the codec name :rtype: str def get_canonical_encoding_name(name): # type: (str) -> str """ Given an encoding name, get the canonical name from ...
Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream. :param stream: A stream instance to wrap :returns: A new, wrapped stream :rtype: :class:`StreamWrapper` def get_wrapped_stream(stream): """ Given a stream, wrap it in a `StreamWrapper` instance and return the wrap...
Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. def is_connection_dropped(conn): # Plat...
Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the...
Returns True if the system can bind an IPv6 address. def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here...
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). def _parse_local_version(local): """ Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). """ if local is not None: return tuple( part.lower() if not part.isdigit() else int(part) ...
Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to ...
Raise an option parsing error using parser.error(). Args: parser: an OptionParser instance. option: an Option instance. msg: the error text. def raise_option_error(parser, option, msg): """ Raise an option parsing error using parser.error(). Args: parser: an OptionParser insta...
Return an OptionGroup object group -- assumed to be dict with 'name' and 'options' keys parser -- an optparse Parser def make_option_group(group, parser): # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup """ Return an OptionGroup object group -- assumed to be dict with 'name' and '...
Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """D...
Function for determining if custom platform options are allowed. :param options: The OptionParser options. :param check_target: Whether or not to check if --target is being used. def check_dist_restriction(options, check_target=False): # type: (Values, bool) -> None """Function for determining if cust...
Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir option. def no_cache_dir_callback(option, opt, value, parser): """ Process a value provided for the --no-cache-dir option. This is an optparse.Option callback for the --no-cache-dir opti...
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 opt...
Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo name. def _merge_hash(option, opt_str, value, parser): # type: (Option, str, str, OptionParser) -> None """Given a value spelled "algo:digest", append the digest to a list pointed to in a dict by the algo ...
Derive missing values of source from the existing fields. def populate_source(cls, source): """Derive missing values of source from the existing fields.""" # Only URL pararemter is mandatory, let the KeyError be thrown. if "name" not in source: source["name"] = get_url_name(source["...
Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned django>1.8 # NOT pinned ...
Returns a new requirement object with extras removed. def strip_extras(requirement): """Returns a new requirement object with extras removed. """ line = requirement.as_line() new = type(requirement).from_line(line) new.extras = None return new
In the string `path`, replace tokens like {some.thing} with the corresponding value from the map `local_vars`. If there is no corresponding value, leave the token unchanged. def _subst_vars(path, local_vars): """In the string `path`, replace tokens like {some.thing} with the corresponding value from t...
Return the path of the Makefile. def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") if hasattr(sys, 'abiflags'): config_dir_name = 'config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags) else: config_dir...
Initialize the module as appropriate for POSIX systems. def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Pyt...
Initialize the module as appropriate for NT def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' ...
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is...
Return the path of pyconfig.h. def get_config_h_filename(): """Return the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return...
Return a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Return a mapping containing an install scheme. ``scheme`` is the i...
Return a path corresponding to the scheme. ``scheme`` is the install scheme name. def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Return a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name]
Display all information sysconfig detains. def _main(): """Display all information sysconfig detains.""" print('Platform: "%s"' % get_platform()) print('Python version: "%s"' % get_python_version()) print('Current installation scheme: "%s"' % _get_default_scheme()) print() _print_dict('Paths', ...
Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or ...
Increments the parser by n characters if the end of the input has not been reached. def inc_n(self, n, exception=None): # type: (int, Exception) -> bool """ Increments the parser by n characters if the end of the input has not been reached. """ for _ in range(n): ...
Consume chars until min/max is satisfied is valid. def consume(self, chars, min=0, max=-1): """ Consume chars until min/max is satisfied is valid. """ while self.current in chars and max != 0: min -= 1 max -= 1 if not self.inc(): break...
Creates a generic "parse error" at the current position. def parse_error( self, exception=ParseError, *args ): # type: (ParseError.__class__, ...) -> ParseError """ Creates a generic "parse error" at the current position. """ line, col = self._to_linecol() return e...
Yields sorted (command name, command summary) tuples. def get_summaries(ordered=True): """Yields sorted (command name, command summary) tuples.""" if ordered: cmditems = _sort_commands(commands_dict, commands_order) else: cmditems = commands_dict.items() for name, command_class in cmd...
Command name auto-correct. def get_similar_commands(name): """Command name auto-correct.""" from difflib import get_close_matches name = name.lower() close_commands = get_close_matches(name, commands_dict.keys()) if close_commands: return close_commands[0] else: return False
Create a copy of this extension bound to another environment. def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful ...
Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :cla...
Parse a translatable tag. def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno num_called_num = False # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked a...
Parse until the next block tag with a given name. def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.curr...
Generates a useful node from the data provided. def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocat...
Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command. def get_cli_string(path=None, action=None, key=None, value=None, quote=None): """Returns a string suitable for running as a shell script. Usef...
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary beca...
Receives a Response. Returns a redirect URI or ``None`` def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least t...
Decide whether Authorization header should be removed when redirecting def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_...
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. def rebuild_auth(self, prepared_request, response): """When being redirected we may wa...
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). ...
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this ...
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the...
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` objec...
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Res...
r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` ob...
Send a given PreparedRequest. :rtype: requests.Response def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the prev...
Check the environment and merge it with some settings. :rtype: dict def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. ...
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.ada...
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter ...
Return a string, safe for output, of subprocess output. We assume the data is in the locale preferred encoding. If it won't decode properly, we warn the user but decode as best we can. We also ensure that the output can be safely written to standard output without encoding errors. def console_to_...
Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is a symlink or can't be read. def get_path_uid(path): # t...
Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 def expanduser(path): # type: (str) -> str """ Expand ~ and ~user constructions. Includes a workaround for https://bugs.python.org/issue14768 """ expanded = os.path.expanduser(path) if path....
Provide an alternative for os.path.samefile on Windows/Python2 def samefile(file1, file2): # type: (str, str) -> bool """Provide an alternative for os.path.samefile on Windows/Python2""" if hasattr(os.path, 'samefile'): return os.path.samefile(file1, file2) else: path1 = os.path.normcas...
Mutate the current entry to ensure that we are making the smallest amount of changes possible to the existing lockfile -- this will keep the old locked versions of packages if they satisfy new constraints. :return: None def ensure_least_updates_possible(self): """ Mutate the cu...
Retrieve all of the relevant constraints, aggregated from the pipfile, resolver, and parent dependencies and their respective conflict resolution where possible. :return: A set of **InstallRequirement** instances representing constraints :rtype: Set def get_constraints(self): """ ...
Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if...
Retrieves the full set of available constraints and iterate over them, validating that they exist and that they are not causing unresolvable conflicts. :return: True if the constraints are satisfied by the resolution provided :raises: :exc:`pipenv.exceptions.DependencyConflict` if the constrain...
Monkey-patch urllib3 with SecureTransport-backed SSL-support. def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True ...
Undo monkey-patching by :func:`inject_into_urllib3`. def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False ...
SecureTransport read callback. This is called by ST to request that data be returned from the socket. def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket...
SecureTransport write callback. This is called by ST to request that data actually be sent on the network. def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wra...
A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the soc...
Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. def _set_ciphers(self): ...
Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: ...
Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, ...
Dump the bytecode into the file or file like object passed. def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError('can\'t write empty bucket') f.write(bc_magic) pickle.dump(self.checksum, f, 2) ...
Returns the unique hash key for this template name. def get_cache_key(self, name, filename=None): """Returns the unique hash key for this template name.""" hash = sha1(name.encode('utf-8')) if filename is not None: filename = '|' + filename if isinstance(filename, text_t...
Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. def get_bucket(self, environment, name, filename, source): """Return a cache bucket for the given template. All arguments are mandatory but filename may be `None`. """ key = s...
Look for an encoding by its label. This is the spec’s `get an encoding <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. Supported labels are listed there. :param label: A string. :returns: An :class:`Encoding` object, or :obj:`None` for an unknown label. def lookup(labe...
Accept either an encoding object or label. :param encoding: An :class:`Encoding` object or a label string. :returns: An :class:`Encoding` object. :raises: :exc:`~exceptions.LookupError` for an unknown label. def _get_encoding(encoding_or_label): """ Accept either an encoding object or label. ...
Decode a single string. :param input: A byte string :param fallback_encoding: An :class:`Encoding` object or a label string. The encoding to use if :obj:`input` does note have a BOM. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupErr...
Return (bom_encoding, input), with any BOM removed from the input. def _detect_bom(input): """Return (bom_encoding, input), with any BOM removed from the input.""" if input.startswith(b'\xFF\xFE'): return _UTF16LE, input[2:] if input.startswith(b'\xFE\xFF'): return _UTF16BE, input[2:] i...
Encode a single string. :param input: An Unicode string. :param encoding: An :class:`Encoding` object or a label string. :param errors: Type of error handling. See :func:`codecs.register`. :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. :return: A byte string. def encode(inp...
"Pull"-based decoder. :param input: An iterable of byte strings. The input is first consumed just enough to determine the encoding based on the precense of a BOM, then consumed on demand when the return value is. :param fallback_encoding: An :class:`Encoding` object or ...
Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings. def _iter_decode_generator(input, decoder): """Return a generator that first yields the :obj:`Encoding`, then yields output chukns as Unicode strings. """ decode = decoder.decode input = ite...