Revert fec8e404 and 6a55c56f in order to fix building dmg

GitOrigin-RevId: 02f6104ca8bbd91cbac617af07161f46cc68159e
This commit is contained in:
Semyon Proshev
2019-09-30 16:34:17 +00:00
committed by intellij-monorepo-bot
parent dc86e49dd0
commit 26ecc11963
40 changed files with 23879 additions and 218 deletions
@@ -0,0 +1,11 @@
"""Skeleton for 'logging' stdlib module."""
import logging
def getLogger(name=None):
"""
:type name: string
:rtype: logging.Logger
"""
pass
@@ -0,0 +1,280 @@
"""Skeleton for 'multiprocessing' stdlib module."""
from multiprocessing.pool import Pool
class Process(object):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
self.name = ''
self.daemon = False
self.authkey = None
self.exitcode = None
self.ident = 0
self.pid = 0
self.sentinel = None
def run(self):
pass
def start(self):
pass
def terminate(self):
pass
def join(self, timeout=None):
pass
def is_alive(self):
return False
class ProcessError(Exception):
pass
class BufferTooShort(ProcessError):
pass
class AuthenticationError(ProcessError):
pass
class TimeoutError(ProcessError):
pass
class Connection(object):
def send(self, obj):
pass
def recv(self):
pass
def fileno(self):
return 0
def close(self):
pass
def poll(self, timeout=None):
pass
def send_bytes(self, buffer, offset=-1, size=-1):
pass
def recv_bytes(self, maxlength=-1):
pass
def recv_bytes_into(self, buffer, offset=-1):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def Pipe(duplex=True):
return Connection(), Connection()
class Queue(object):
def __init__(self, maxsize=-1):
self._maxsize = maxsize
def qsize(self):
return 0
def empty(self):
return False
def full(self):
return False
def put(self, obj, block=True, timeout=None):
pass
def put_nowait(self, obj):
pass
def get(self, block=True, timeout=None):
pass
def get_nowait(self):
pass
def close(self):
pass
def join_thread(self):
pass
def cancel_join_thread(self):
pass
class SimpleQueue(object):
def empty(self):
return False
def get(self):
pass
def put(self, item):
pass
class JoinableQueue(multiprocessing.Queue):
def task_done(self):
pass
def join(self):
pass
def active_children():
"""
:rtype: list[multiprocessing.Process]
"""
return []
def cpu_count():
return 0
def current_process():
"""
:rtype: multiprocessing.Process
"""
return Process()
def freeze_support():
pass
def get_all_start_methods():
return []
def get_context(method=None):
pass
def get_start_method(allow_none=False):
pass
def set_executable(path):
pass
def set_start_method(method):
pass
class Barrier(object):
def __init__(self, parties, action=None, timeout=None):
self.parties = parties
self.n_waiting = 0
self.broken = False
def wait(self, timeout=None):
pass
def reset(self):
pass
def abort(self):
pass
class Semaphore(object):
def __init__(self, value=1):
pass
def acquire(self, blocking=True, timeout=None):
pass
def release(self):
pass
class BoundedSemaphore(multiprocessing.Semaphore):
pass
class Condition(object):
def __init__(self, lock=None):
pass
def acquire(self, *args):
pass
def release(self):
pass
def wait(self, timeout=None):
pass
def wait_for(self, predicate, timeout=None):
pass
def notify(self, n=1):
pass
def notify_all(self):
pass
class Event(object):
def is_set(self):
return False
def set(self):
pass
def clear(self):
pass
def wait(self, timeout=None):
pass
class Lock(object):
def acquire(self, blocking=True, timeout=-1):
pass
def release(self):
pass
class RLock(object):
def acquire(self, blocking=True, timeout=-1):
pass
def release(self):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def Value(typecode_or_type, *args, **kwargs):
pass
def Array(typecode_or_type, size_or_initializer, lock=True):
pass
def Manager():
return multiprocessing.SyncManager()
@@ -0,0 +1,76 @@
"""Skeleton for 'multiprocessing.managers' stdlib module."""
import threading
import queue
import multiprocessing
import multiprocessing.managers
class BaseManager(object):
def __init__(self, address=None, authkey=None):
self.address = address
def start(self, initializer=None, initargs=None):
pass
def get_server(self):
pass
def connect(self):
pass
def shutdown(self):
pass
@classmethod
def register(cls, typeid, callable=None, proxytype=None, exposed=None,
method_to_typeid=None, create_method=None):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class SyncManager(multiprocessing.managers.BaseManager):
def Barrier(self, parties, action=None, timeout=None):
return threading.Barrier(parties, action, timeout)
def BoundedSemaphore(self, value=None):
return threading.BoundedSemaphore(value)
def Condition(self, lock=None):
return threading.Condition(lock)
def Event(self):
return threading.Event()
def Lock(self):
return threading.Lock()
def Namespace(self):
pass
def Queue(self, maxsize=None):
return queue.Queue()
def RLock(self):
return threading.RLock()
def Semaphore(self, value=None):
return threading.Semaphore(value)
def Array(self, typecode, sequence):
pass
def Value(self, typecode, value):
pass
def dict(self, mapping_or_sequence):
pass
def list(self, sequence):
pass
+9
View File
@@ -0,0 +1,9 @@
"""Skeleton for 'sys' stdlib module."""
def getsizeof(object, default=None):
"""
:type default: T | None
:rtype: int | T
"""
return 0
+601
View File
@@ -0,0 +1,601 @@
# Copyright 2007 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
via collections; they are defined here only to alleviate certain
bootstrapping issues. Unit tests are in test_collections.
"""
from abc import ABCMeta, abstractmethod
import sys
__all__ = ["Hashable", "Iterable", "Iterator",
"Sized", "Container", "Callable",
"Set", "MutableSet",
"Mapping", "MutableMapping",
"MappingView", "KeysView", "ItemsView", "ValuesView",
"Sequence", "MutableSequence",
]
### ONE-TRICK PONIES ###
def _hasattr(C, attr):
try:
return any(attr in B.__dict__ for B in C.__mro__)
except AttributeError:
# Old-style class
return hasattr(C, attr)
class Hashable:
__metaclass__ = ABCMeta
@abstractmethod
def __hash__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Hashable:
try:
for B in C.__mro__:
if "__hash__" in B.__dict__:
if B.__dict__["__hash__"]:
return True
break
except AttributeError:
# Old-style class
if getattr(C, "__hash__", None):
return True
return NotImplemented
class Iterable:
__metaclass__ = ABCMeta
@abstractmethod
def __iter__(self):
while False:
yield None
@classmethod
def __subclasshook__(cls, C):
if cls is Iterable:
if _hasattr(C, "__iter__"):
return True
return NotImplemented
Iterable.register(str)
class Iterator(Iterable):
@abstractmethod
def next(self):
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
if _hasattr(C, "next") and _hasattr(C, "__iter__"):
return True
return NotImplemented
class Sized:
__metaclass__ = ABCMeta
@abstractmethod
def __len__(self):
return 0
@classmethod
def __subclasshook__(cls, C):
if cls is Sized:
if _hasattr(C, "__len__"):
return True
return NotImplemented
class Container:
__metaclass__ = ABCMeta
@abstractmethod
def __contains__(self, x):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Container:
if _hasattr(C, "__contains__"):
return True
return NotImplemented
class Callable:
__metaclass__ = ABCMeta
@abstractmethod
def __call__(self, *args, **kwds):
return False
@classmethod
def __subclasshook__(cls, C):
if cls is Callable:
if _hasattr(C, "__call__"):
return True
return NotImplemented
### SETS ###
class Set(Sized, Iterable, Container):
"""A set is a finite, iterable container.
This class provides concrete generic implementations of all
methods except for __contains__, __iter__ and __len__.
To override the comparisons (presumably for speed, as the
semantics are fixed), all you have to do is redefine __le__ and
then the other operations will automatically follow suit.
"""
def __le__(self, other):
if not isinstance(other, Set):
return NotImplemented
if len(self) > len(other):
return False
for elem in self:
if elem not in other:
return False
return True
def __lt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) < len(other) and self.__le__(other)
def __gt__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other < self
def __ge__(self, other):
if not isinstance(other, Set):
return NotImplemented
return other <= self
def __eq__(self, other):
if not isinstance(other, Set):
return NotImplemented
return len(self) == len(other) and self.__le__(other)
def __ne__(self, other):
return not (self == other)
@classmethod
def _from_iterable(cls, it):
'''Construct an instance of the class from any iterable input.
Must override this method if the class constructor signature
does not accept an iterable for an input.
'''
return cls(it)
def __and__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
return self._from_iterable(value for value in other if value in self)
def isdisjoint(self, other):
for value in other:
if value in self:
return False
return True
def __or__(self, other):
if not isinstance(other, Iterable):
return NotImplemented
chain = (e for s in (self, other) for e in s)
return self._from_iterable(chain)
def __sub__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return self._from_iterable(value for value in self
if value not in other)
def __xor__(self, other):
if not isinstance(other, Set):
if not isinstance(other, Iterable):
return NotImplemented
other = self._from_iterable(other)
return (self - other) | (other - self)
# Sets are not hashable by default, but subclasses can change this
__hash__ = None
def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
elements, regardless of how they are implemented, and
regardless of the order of the elements; so there's not much
freedom for __eq__ or __hash__. We match the algorithm used
by the built-in frozenset type.
"""
MAX = sys.maxint
MASK = 2 * MAX + 1
n = len(self)
h = 1927868237 * (n + 1)
h &= MASK
for x in self:
hx = hash(x)
h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
h &= MASK
h = h * 69069 + 907133923
h &= MASK
if h > MAX:
h -= MASK + 1
if h == -1:
h = 590923713
return h
Set.register(frozenset)
class MutableSet(Set):
@abstractmethod
def add(self, value):
"""Add an element."""
raise NotImplementedError
@abstractmethod
def discard(self, value):
"""Remove an element. Do not raise an exception if absent."""
raise NotImplementedError
def remove(self, value):
"""Remove an element. If not a member, raise a KeyError."""
if value not in self:
raise KeyError(value)
self.discard(value)
def pop(self):
"""Return the popped value. Raise KeyError if empty."""
it = iter(self)
try:
value = next(it)
except StopIteration:
raise KeyError
self.discard(value)
return value
def clear(self):
"""This is slow (creates N new iterators!) but effective."""
try:
while True:
self.pop()
except KeyError:
pass
def __ior__(self, it):
for value in it:
self.add(value)
return self
def __iand__(self, it):
for value in (self - it):
self.discard(value)
return self
def __ixor__(self, it):
if it is self:
self.clear()
else:
if not isinstance(it, Set):
it = self._from_iterable(it)
for value in it:
if value in self:
self.discard(value)
else:
self.add(value)
return self
def __isub__(self, it):
if it is self:
self.clear()
else:
for value in it:
self.discard(value)
return self
MutableSet.register(set)
### MAPPINGS ###
class Mapping(Sized, Iterable, Container):
@abstractmethod
def __getitem__(self, key):
raise KeyError
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def iterkeys(self):
return iter(self)
def itervalues(self):
for key in self:
yield self[key]
def iteritems(self):
for key in self:
yield (key, self[key])
def keys(self):
return list(self)
def items(self):
return [(key, self[key]) for key in self]
def values(self):
return [self[key] for key in self]
# Mappings are not hashable by default, but subclasses can change this
__hash__ = None
def __eq__(self, other):
if not isinstance(other, Mapping):
return NotImplemented
return dict(self.items()) == dict(other.items())
def __ne__(self, other):
return not (self == other)
class MappingView(Sized):
def __init__(self, mapping):
self._mapping = mapping
def __len__(self):
return len(self._mapping)
def __repr__(self):
return '{0.__class__.__name__}({0._mapping!r})'.format(self)
class KeysView(MappingView, Set):
@classmethod
def _from_iterable(self, it):
return set(it)
def __contains__(self, key):
return key in self._mapping
def __iter__(self):
for key in self._mapping:
yield key
class ItemsView(MappingView, Set):
@classmethod
def _from_iterable(self, it):
return set(it)
def __contains__(self, item):
key, value = item
try:
v = self._mapping[key]
except KeyError:
return False
else:
return v == value
def __iter__(self):
for key in self._mapping:
yield (key, self._mapping[key])
class ValuesView(MappingView):
def __contains__(self, value):
for key in self._mapping:
if value == self._mapping[key]:
return True
return False
def __iter__(self):
for key in self._mapping:
yield self._mapping[key]
class MutableMapping(Mapping):
@abstractmethod
def __setitem__(self, key, value):
raise KeyError
@abstractmethod
def __delitem__(self, key):
raise KeyError
__marker = object()
def pop(self, key, default=__marker):
try:
value = self[key]
except KeyError:
if default is self.__marker:
raise
return default
else:
del self[key]
return value
def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
value = self[key]
del self[key]
return key, value
def clear(self):
try:
while True:
self.popitem()
except KeyError:
pass
def update(*args, **kwds):
if len(args) > 2:
raise TypeError("update() takes at most 2 positional "
"arguments ({} given)".format(len(args)))
elif not args:
raise TypeError("update() takes at least 1 argument (0 given)")
self = args[0]
other = args[1] if len(args) >= 2 else ()
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
def setdefault(self, key, default=None):
try:
return self[key]
except KeyError:
self[key] = default
return default
MutableMapping.register(dict)
### SEQUENCES ###
class Sequence(Sized, Iterable, Container):
"""All the operations on a read-only sequence.
Concrete subclasses must override __new__ or __init__,
__getitem__, and __len__.
"""
@abstractmethod
def __getitem__(self, index):
raise IndexError
def __iter__(self):
i = 0
try:
while True:
v = self[i]
yield v
i += 1
except IndexError:
return
def __contains__(self, value):
for v in self:
if v == value:
return True
return False
def __reversed__(self):
for i in reversed(range(len(self))):
yield self[i]
def index(self, value):
for i, v in enumerate(self):
if v == value:
return i
raise ValueError
def count(self, value):
return sum(1 for v in self if v == value)
Sequence.register(tuple)
Sequence.register(basestring)
Sequence.register(buffer)
Sequence.register(xrange)
class MutableSequence(Sequence):
@abstractmethod
def __setitem__(self, index, value):
raise IndexError
@abstractmethod
def __delitem__(self, index):
raise IndexError
@abstractmethod
def insert(self, index, value):
raise IndexError
def append(self, value):
self.insert(len(self), value)
def reverse(self):
n = len(self)
for i in range(n//2):
self[i], self[n-i-1] = self[n-i-1], self[i]
def extend(self, values):
for v in values:
self.append(v)
def pop(self, index=-1):
v = self[index]
del self[index]
return v
def remove(self, value):
del self[self.index(value)]
def __iadd__(self, values):
self.extend(values)
return self
MutableSequence.register(list)
@@ -0,0 +1,668 @@
__all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict']
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
# They should however be considered an integral part of collections.py.
from _abcoll import *
import _abcoll
__all__ += _abcoll.__all__
from _collections import deque, defaultdict
from operator import itemgetter as _itemgetter
from keyword import iskeyword as _iskeyword
import sys as _sys
import heapq as _heapq
from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
################################################################################
### OrderedDict
################################################################################
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].
def __init__(self, *args, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries, but keyword arguments are not recommended because
their insertion order is arbitrary.
'''
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__root = root = [] # sentinel node
root[:] = [root, root, None]
self.__map = {}
self.__update(*args, **kwds)
def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
root = self.__root
last = root[PREV]
last[NEXT] = root[PREV] = self.__map[key] = [last, root, key]
dict_setitem(self, key, value)
def __delitem__(self, key, PREV=0, NEXT=1, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
NEXT, KEY = 1, 2
root = self.__root
curr = root[NEXT]
while curr is not root:
yield curr[KEY]
curr = curr[NEXT]
def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
PREV, KEY = 0, 2
root = self.__root
curr = root[PREV]
while curr is not root:
yield curr[KEY]
curr = curr[PREV]
def clear(self):
'od.clear() -> None. Remove all items from od.'
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
dict.clear(self)
# -- the following methods do not depend on the internal structure --
def keys(self):
'od.keys() -> list of keys in od'
return list(self)
def values(self):
'od.values() -> list of values in od'
return [self[key] for key in self]
def items(self):
'od.items() -> list of (key, value) pairs in od'
return [(key, self[key]) for key in self]
def iterkeys(self):
'od.iterkeys() -> an iterator over the keys in od'
return iter(self)
def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k]
def iteritems(self):
'od.iteritems -> an iterator over the (key, value) pairs in od'
for k in self:
yield (k, self[k])
update = MutableMapping.update
__update = update # let subclasses override update without breaking __init__
__marker = object()
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
if key in self:
return self[key]
self[key] = default
return default
def popitem(self, last=True):
'''od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false.
'''
if not self:
raise KeyError('dictionary is empty')
key = next(reversed(self) if last else iter(self))
value = self.pop(key)
return key, value
def __repr__(self, _repr_running={}):
'od.__repr__() <==> repr(od)'
call_key = id(self), _get_ident()
if call_key in _repr_running:
return '...'
_repr_running[call_key] = 1
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
finally:
del _repr_running[call_key]
def __reduce__(self):
'Return state information for pickling'
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None.
'''
self = cls()
for key in iterable:
self[key] = value
return self
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
'od.__ne__(y) <==> od!=y'
return not self == other
# -- the following methods support python 3.x style dictionary views --
def viewkeys(self):
"od.viewkeys() -> a set-like object providing a view on od's keys"
return KeysView(self)
def viewvalues(self):
"od.viewvalues() -> an object providing a view on od's values"
return ValuesView(self)
def viewitems(self):
"od.viewitems() -> a set-like object providing a view on od's items"
return ItemsView(self)
################################################################################
### namedtuple
################################################################################
def namedtuple(typename, field_names, verbose=False, rename=False):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y')
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
# Parse and validate the field names. Validation serves two purposes,
# generating informative error messages and preventing template injection attacks.
if isinstance(field_names, basestring):
field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
field_names = tuple(map(str, field_names))
if rename:
names = list(field_names)
seen = set()
for i, name in enumerate(names):
if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
or not name or name[0].isdigit() or name.startswith('_')
or name in seen):
names[i] = '_%d' % i
seen.add(name)
field_names = tuple(names)
for name in (typename,) + field_names:
if not all(c.isalnum() or c=='_' for c in name):
raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a keyword: %r' % name)
if name[0].isdigit():
raise ValueError('Type names and field names cannot start with a number: %r' % name)
seen_names = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: %r' % name)
if name in seen_names:
raise ValueError('Encountered duplicate field name: %r' % name)
seen_names.add(name)
# Create and fill-in the class template
numfields = len(field_names)
argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
template = '''class %(typename)s(tuple):
'%(typename)s(%(argtxt)s)' \n
__slots__ = () \n
_fields = %(field_names)r \n
def __new__(_cls, %(argtxt)s):
'Create new instance of %(typename)s(%(argtxt)s)'
return _tuple.__new__(_cls, (%(argtxt)s)) \n
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new %(typename)s object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != %(numfields)d:
raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
return result \n
def __repr__(self):
'Return a nicely formatted representation string'
return '%(typename)s(%(reprtxt)s)' %% self \n
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(zip(self._fields, self)) \n
__dict__ = property(_asdict) \n
def _replace(_self, **kwds):
'Return a new %(typename)s object replacing specified fields with new values'
result = _self._make(map(kwds.pop, %(field_names)r, _self))
if kwds:
raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
return result \n
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self) \n\n''' % locals()
for i, name in enumerate(field_names):
template += " %s = _property(_itemgetter(%d), doc='Alias for field number %d')\n" % (name, i, i)
if verbose:
print template
# Execute the template string in a temporary namespace and
# support tracing utilities by setting a value for frame.f_globals['__name__']
namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
OrderedDict=OrderedDict, _property=property, _tuple=tuple)
try:
exec template in namespace
except SyntaxError, e:
raise SyntaxError(e.message + ':\n' + template)
result = namespace[typename]
# For pickling to work, the __module__ variable needs to be set to the frame
# where the named tuple is created. Bypass this step in enviroments where
# sys._getframe is not defined (Jython for example) or sys._getframe is not
# defined for arguments greater than 0 (IronPython).
try:
result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return result
########################################################################
### Counter
########################################################################
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c) # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements())) # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values()) # total of all counts
15
>>> c['a'] # count of letter 'a'
5
>>> for elem in 'shazam': # update counts from an iterable
... c[elem] += 1 # by adding 1 to each element's count
>>> c['a'] # now there are seven 'a'
7
>>> del c['b'] # remove all 'b'
>>> c['b'] # now there are zero 'b'
0
>>> d = Counter('simsalabim') # make another counter
>>> c.update(d) # add in the second counter
>>> c['a'] # now there are nine 'a'
9
>>> c.clear() # empty the counter
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc')
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
'''
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6.3
def __init__(self, iterable=None, **kwds):
'''Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
'''
super(Counter, self).__init__()
self.update(iterable, **kwds)
def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))
def elements(self):
'''Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836
Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.
'''
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.iteritems()))
# Override dict methods where necessary
@classmethod
def fromkeys(cls, iterable, v=None):
# There is no equivalent method for counters because setting v=1
# means that no element can have a count greater than one.
raise NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
def update(self, iterable=None, **kwds):
'''Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.update('witch') # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch
4
'''
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn't have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
# and outputs are allowed to contain zero and negative counts.
if iterable is not None:
if isinstance(iterable, Mapping):
if self:
self_get = self.get
for elem, count in iterable.iteritems():
self[elem] = self_get(elem, 0) + count
else:
super(Counter, self).update(iterable) # fast path when counter is empty
else:
self_get = self.get
for elem in iterable:
self[elem] = self_get(elem, 0) + 1
if kwds:
self.update(kwds)
def subtract(self, iterable=None, **kwds):
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which')
>>> c.subtract('witch') # subtract elements from another iterable
>>> c.subtract(Counter('watch')) # subtract elements from another counter
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
-1
'''
if iterable is not None:
self_get = self.get
if isinstance(iterable, Mapping):
for elem, count in iterable.items():
self[elem] = self_get(elem, 0) - count
else:
for elem in iterable:
self[elem] = self_get(elem, 0) - 1
if kwds:
self.subtract(kwds)
def copy(self):
'Return a shallow copy.'
return self.__class__(self)
def __reduce__(self):
return self.__class__, (dict(self),)
def __delitem__(self, elem):
'Like dict.__delitem__() but does not raise KeyError for missing values.'
if elem in self:
super(Counter, self).__delitem__(elem)
def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
# Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6.3 exercise 19
# and at http://en.wikipedia.org/wiki/Multiset
#
# Outputs guaranteed to only include positive counts.
#
# To strip negative and zero counts, add-in an empty counter:
# c += Counter()
def __add__(self, other):
'''Add counts from two counters.
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
def __sub__(self, other):
''' Subtract count, but keep only results with positive counts.
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count - other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count < 0:
result[elem] = 0 - count
return result
def __or__(self, other):
'''Union is the maximum of value in either of the input counters.
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
def __and__(self, other):
''' Intersection is the minimum of corresponding counts.
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
'''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count
if newcount > 0:
result[elem] = newcount
return result
if __name__ == '__main__':
# verify that instances can be pickled
from cPickle import loads, dumps
Point = namedtuple('Point', 'x, y', True)
p = Point(x=10, y=20)
assert p == loads(dumps(p))
# test and demonstrate ability to override methods
class Point(namedtuple('Point', 'x y')):
__slots__ = ()
@property
def hypot(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def __str__(self):
return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
for p in Point(3, 4), Point(14, 5/7.):
print p
class Point(namedtuple('Point', 'x y')):
'Point class with optimized _make() and _replace() without error-checking'
__slots__ = ()
_make = classmethod(tuple.__new__)
def _replace(self, _map=map, **kwds):
return self._make(_map(kwds.get, ('x', 'y'), self))
print Point(11, 22)._replace(x=100)
Point3D = namedtuple('Point3D', Point._fields + ('z',))
print Point3D.__doc__
import doctest
TestResults = namedtuple('TestResults', 'failed attempted')
print TestResults(*doctest.testmod())
+98
View File
@@ -0,0 +1,98 @@
"""The io module provides the Python interfaces to stream handling. The
builtin open function is defined in this module.
At the top of the I/O hierarchy is the abstract base class IOBase. It
defines the basic interface to a stream. Note, however, that there is no
separation between reading and writing to streams; implementations are
allowed to throw an IOError if they do not support a given operation.
Extending IOBase is RawIOBase which deals simply with the reading and
writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
an interface to OS files.
BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
streams that are readable, writable, and both respectively.
BufferedRandom provides a buffered interface to random access
streams. BytesIO is a simple stream of in-memory bytes.
Another IOBase subclass, TextIOBase, deals with the encoding and decoding
of streams into text. TextIOWrapper, which extends it, is a buffered text
interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
is a in-memory stream for text.
Argument names are not part of the specification, and only the arguments
of open() are intended to be used as keyword arguments.
data:
DEFAULT_BUFFER_SIZE
An int containing the default buffer size used by the module's buffered
I/O classes. open() uses the file's blksize (as obtained by os.stat) if
possible.
"""
# New I/O library conforming to PEP 3116.
# XXX edge cases when switching between reading/writing
# XXX need to support 1 meaning line-buffered
# XXX whenever an argument is None, use the default value
# XXX read/write ops should check readable/writable
# XXX buffered readinto should work with arbitrary buffer objects
# XXX use incremental encoder for text output, at least for UTF-16 and UTF-8-SIG
# XXX check writable, readable and seekable in appropriate places
__author__ = ("Guido van Rossum <guido@python.org>, "
"Mike Verdone <mike.verdone@gmail.com>, "
"Mark Russell <mark.russell@zen.co.uk>, "
"Antoine Pitrou <solipsis@pitrou.net>, "
"Amaury Forgeot d'Arc <amauryfa@gmail.com>, "
"Benjamin Peterson <benjamin@python.org>")
__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
"BytesIO", "StringIO", "BufferedIOBase",
"BufferedReader", "BufferedWriter", "BufferedRWPair",
"BufferedRandom", "TextIOBase", "TextIOWrapper",
"UnsupportedOperation", "SEEK_SET", "SEEK_CUR", "SEEK_END"]
import _io
import abc
from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError, UnsupportedOperation,
open, FileIO, BytesIO, StringIO, BufferedReader,
BufferedWriter, BufferedRWPair, BufferedRandom,
IncrementalNewlineDecoder, TextIOWrapper)
OpenWrapper = _io.open # for compatibility with _pyio
# for seek()
SEEK_SET = 0
SEEK_CUR = 1
SEEK_END = 2
# Declaring ABCs in C is tricky so we do it here.
# Method descriptions and default implementations are inherited from the C
# version however.
class IOBase(_io._IOBase):
__metaclass__ = abc.ABCMeta
class RawIOBase(_io._RawIOBase, IOBase):
pass
class BufferedIOBase(_io._BufferedIOBase, IOBase):
pass
class TextIOBase(_io._TextIOBase, IOBase):
pass
RawIOBase.register(FileIO)
for klass in (BytesIO, BufferedReader, BufferedWriter, BufferedRandom,
BufferedRWPair):
BufferedIOBase.register(klass)
for klass in (StringIO, TextIOWrapper):
TextIOBase.register(klass)
del klass
+326
View File
@@ -0,0 +1,326 @@
#
# Secret Labs' Regular Expression Engine
#
# re-compatible interface for the sre matching engine
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# This version of the SRE library can be redistributed under CNRI's
# Python 1.6 license. For any other use, please contact Secret Labs
# AB (info@pythonware.com).
#
# Portions of this engine have been developed in cooperation with
# CNRI. Hewlett-Packard provided funding for 1.6 integration and
# other compatibility work.
#
r"""Support for regular expressions (RE).
This module provides regular expression matching operations similar to
those found in Perl. It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.
Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like "A", "a", or "0", are the simplest
regular expressions; they simply match themselves. You can
concatenate ordinary characters, so last matches the string 'last'.
The special characters are:
"." Matches any character except a newline.
"^" Matches the start of the string.
"$" Matches the end of the string or just before the newline at
the end of the string.
"*" Matches 0 or more (greedy) repetitions of the preceding RE.
Greedy means that it will match as many repetitions as possible.
"+" Matches 1 or more (greedy) repetitions of the preceding RE.
"?" Matches 0 or 1 (greedy) of the preceding RE.
*?,+?,?? Non-greedy versions of the previous three special characters.
{m,n} Matches from m to n repetitions of the preceding RE.
{m,n}? Non-greedy version of the above.
"\\" Either escapes special characters or signals a special sequence.
[] Indicates a set of characters.
A "^" as the first character indicates a complementing set.
"|" A|B, creates an RE that will match either A or B.
(...) Matches the RE inside the parentheses.
The contents can be retrieved or matched later in the string.
(?iLmsux) Set the I, L, M, S, U, or X flag for the RE (see below).
(?:...) Non-grouping version of regular parentheses.
(?P<name>...) The substring matched by the group is accessible by name.
(?P=name) Matches the text matched earlier by the group named name.
(?#...) A comment; ignored.
(?=...) Matches if ... matches next, but doesn't consume the string.
(?!...) Matches if ... doesn't match next.
(?<=...) Matches if preceded by ... (must be fixed length).
(?<!...) Matches if not preceded by ... (must be fixed length).
(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
the (optional) no pattern otherwise.
The special sequences consist of "\\" and a character from the list
below. If the ordinary character is not on the list, then the
resulting RE will match the second character.
\number Matches the contents of the group of the same number.
\A Matches only at the start of the string.
\Z Matches only at the end of the string.
\b Matches the empty string, but only at the start or end of a word.
\B Matches the empty string, but not at the start or end of a word.
\d Matches any decimal digit; equivalent to the set [0-9].
\D Matches any non-digit character; equivalent to the set [^0-9].
\s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
\S Matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
With LOCALE, it will match the set [0-9_] plus characters defined
as letters for the current locale.
\W Matches the complement of \w.
\\ Matches a literal backslash.
This module exports the following functions:
match Match a regular expression pattern to the beginning of a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a match object for each match.
compile Compile a pattern into a RegexObject.
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
Some of the functions in this module takes flags as optional parameters:
I IGNORECASE Perform case-insensitive matching.
L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
M MULTILINE "^" matches the beginning of lines (after a newline)
as well as the string.
"$" matches the end of lines (before a newline) as well
as the end of the string.
S DOTALL "." matches any character at all, including the newline.
X VERBOSE Ignore whitespace and comments for nicer looking RE's.
U UNICODE Make \w, \W, \b, \B, dependent on the Unicode locale.
This module also defines an exception 'error'.
"""
import sys
import sre_compile
import sre_parse
# public symbols
__all__ = [ "match", "search", "sub", "subn", "split", "findall",
"compile", "purge", "template", "escape", "I", "L", "M", "S", "X",
"U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
"UNICODE", "error" ]
__version__ = "2.2.1"
# flags
I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode locale
M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
# sre extensions (experimental, don't rely on these)
T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
# sre exception
error = sre_compile.error
# --------------------------------------------------------------------
# public interface
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).search(string)
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the match object and must return
a replacement string to be used."""
return _compile(pattern, flags).sub(repl, string, count)
def subn(pattern, repl, string, count=0, flags=0):
"""Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the match object and must
return a replacement string to be used."""
return _compile(pattern, flags).subn(repl, string, count)
def split(pattern, string, maxsplit=0, flags=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings."""
return _compile(pattern, flags).split(string, maxsplit)
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
if sys.hexversion >= 0x02020000:
__all__.append("finditer")
def finditer(pattern, string, flags=0):
"""Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a match object.
Empty matches are included in the result."""
return _compile(pattern, flags).finditer(string)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
return _compile(pattern, flags)
def purge():
"Clear the regular expression cache"
_cache.clear()
_cache_repl.clear()
def template(pattern, flags=0):
"Compile a template pattern, returning a pattern object"
return _compile(pattern, flags|T)
_alphanum = {}
for c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890':
_alphanum[c] = 1
del c
def escape(pattern):
"Escape all non-alphanumeric characters in pattern."
s = list(pattern)
alphanum = _alphanum
for i, c in enumerate(pattern):
if c not in alphanum:
if c == "\000":
s[i] = "\\000"
else:
s[i] = "\\" + c
return pattern[:0].join(s)
# --------------------------------------------------------------------
# internals
_cache = {}
_cache_repl = {}
_pattern_type = type(sre_compile.compile("", 0))
_MAXCACHE = 100
def _compile(*key):
# internal: compile pattern
cachekey = (type(key[0]),) + key
p = _cache.get(cachekey)
if p is not None:
return p
pattern, flags = key
if isinstance(pattern, _pattern_type):
if flags:
raise ValueError('Cannot process flags argument with a compiled pattern')
return pattern
if not sre_compile.isstring(pattern):
raise TypeError, "first argument must be string or compiled pattern"
try:
p = sre_compile.compile(pattern, flags)
except error, v:
raise error, v # invalid expression
if len(_cache) >= _MAXCACHE:
_cache.clear()
_cache[cachekey] = p
return p
def _compile_repl(*key):
# internal: compile replacement pattern
p = _cache_repl.get(key)
if p is not None:
return p
repl, pattern = key
try:
p = sre_parse.parse_template(repl, pattern)
except error, v:
raise error, v # invalid expression
if len(_cache_repl) >= _MAXCACHE:
_cache_repl.clear()
_cache_repl[key] = p
return p
def _expand(pattern, match, template):
# internal: match.expand implementation hook
template = sre_parse.parse_template(template, pattern)
return sre_parse.expand_template(template, match)
def _subx(pattern, template):
# internal: pattern.sub/subn implementation helper
template = _compile_repl(template, pattern)
if not template[0] and len(template[1]) == 1:
# literal replacement
return template[1][0]
def filter(match, template=template):
return sre_parse.expand_template(template, match)
return filter
# register myself for pickling
import copy_reg
def _pickle(p):
return _compile, (p.pattern, p.flags)
copy_reg.pickle(_pattern_type, _pickle, _compile)
# --------------------------------------------------------------------
# experimental stuff (see python-dev discussions for details)
class Scanner:
def __init__(self, lexicon, flags=0):
from sre_constants import BRANCH, SUBPATTERN
self.lexicon = lexicon
# combine phrases into a compound pattern
p = []
s = sre_parse.Pattern()
s.flags = flags
for phrase, action in lexicon:
p.append(sre_parse.SubPattern(s, [
(SUBPATTERN, (len(p)+1, sre_parse.parse(phrase, flags))),
]))
s.groups = len(p)+1
p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
self.scanner = sre_compile.compile(p)
def scan(self, string):
result = []
append = result.append
match = self.scanner.scanner(string).match
i = 0
while 1:
m = match()
if not m:
break
j = m.end()
if i == j:
break
action = self.lexicon[m.lastindex-1][1]
if hasattr(action, '__call__'):
self.match = m
action = action(self, m.group())
if action is not None:
append(action)
i = j
return result, string[i:]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,627 @@
# encoding: utf-8
# module datetime
# from /Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/lib-dynload/datetime.so
# by generator 1.137
""" Fast implementation of the datetime type. """
# no imports
# Variables with simple values
MAXYEAR = 9999
MINYEAR = 1
# no functions
# classes
class date(object):
""" date(year, month, day) --> date object """
def ctime(self): # real signature unknown; restored from __doc__
""" Return ctime() style string. """
pass
@classmethod
def fromordinal(cls, ordinal): # known case of datetime.date.fromordinal
""" int -> date corresponding to a proleptic Gregorian ordinal. """
return date(1,1,1)
@classmethod
def fromtimestamp(cls, timestamp): # known case of datetime.date.fromtimestamp
""" timestamp -> local date from a POSIX timestamp (like time.time()). """
return date(1,1,1)
def isocalendar(self): # known case of datetime.date.isocalendar
""" Return a 3-tuple containing ISO year, week number, and weekday. """
return (1, 1, 1)
def isoformat(self): # known case of datetime.date.isoformat
""" Return string in ISO 8601 format, YYYY-MM-DD. """
return ""
def isoweekday(self): # known case of datetime.date.isoweekday
"""
Return the day of the week represented by the date.
Monday == 1 ... Sunday == 7
"""
return 0
def replace(self, year=None, month=None, day=None): # known case of datetime.date.replace
""" Return date with new specified fields. """
return date(1,1,1)
def strftime(self, format): # known case of datetime.date.strftime
""" format -> strftime() style string. """
return ""
def timetuple(self): # known case of datetime.date.timetuple
""" Return time tuple, compatible with time.localtime(). """
return (0, 0, 0, 0, 0, 0, 0, 0, 0)
@classmethod
def today(self): # known case of datetime.date.today
""" Current date or datetime: same as self.__class__.fromtimestamp(time.time()). """
return date(1, 1, 1)
def toordinal(self): # known case of datetime.date.toordinal
""" Return proleptic Gregorian ordinal. January 1 of year 1 is day 1. """
return 0
def weekday(self): # known case of datetime.date.weekday
"""
Return the day of the week represented by the date.
Monday == 0 ... Sunday == 6
"""
return 0
def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __format__(self, *args, **kwargs): # real signature unknown
""" Formats self with strftime. """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __init__(self, year, month, day): # real signature unknown; restored from __doc__
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
@staticmethod # known case of __new__
def __new__(cls, year=None, month=None, day=None): # known case of datetime.date.__new__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __radd__(self, y): # real signature unknown; restored from __doc__
""" x.__radd__(y) <==> y+x """
pass
def __reduce__(self): # real signature unknown; restored from __doc__
""" __reduce__() -> (cls, state) """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
""" x.__sub__(y) <==> x-y """
pass
day = property(lambda self: 0)
""":type: int"""
month = property(lambda self: 0)
""":type: int"""
year = property(lambda self: 0)
""":type: int"""
max = None # (!) real value is ''
min = None # (!) real value is ''
resolution = None # (!) real value is ''
class datetime(date):
"""
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints or longs.
"""
def astimezone(self, tz): # known case of datetime.datetime.astimezone
""" tz -> convert to local time in new timezone tz """
return datetime(1, 1, 1)
@classmethod
def combine(cls, date, time): # known case of datetime.datetime.combine
""" date, time -> datetime with same date and time fields """
return datetime(1, 1, 1)
def ctime(self): # real signature unknown; restored from __doc__
""" Return ctime() style string. """
pass
def date(self): # known case of datetime.datetime.date
""" Return date object with same year, month and day. """
return datetime(1, 1, 1)
def dst(self): # real signature unknown; restored from __doc__
""" Return self.tzinfo.dst(self). """
pass
@classmethod
def fromtimestamp(cls, timestamp, tz=None): # known case of datetime.datetime.fromtimestamp
""" timestamp[, tz] -> tz's local time from POSIX timestamp. """
return datetime(1, 1, 1)
def isoformat(self, sep='T'): # known case of datetime.datetime.isoformat
"""
[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].
sep is used to separate the year from the time, and defaults to 'T'.
"""
return ""
@classmethod
def now(cls, tz=None): # known case of datetime.datetime.now
""" [tz] -> new datetime with tz's local day and time. """
return datetime(1, 1, 1)
def replace(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): # known case of datetime.datetime.replace
""" Return datetime with new specified fields. """
return datetime(1, 1, 1)
@classmethod
def strptime(cls, date_string, format): # known case of datetime.datetime.strptime
""" string, format -> new datetime parsed from a string (like time.strptime()). """
return ""
def time(self): # known case of datetime.datetime.time
""" Return time object with same time but with tzinfo=None. """
return time(0, 0)
def timetuple(self): # known case of datetime.datetime.timetuple
""" Return time tuple, compatible with time.localtime(). """
return (0, 0, 0, 0, 0, 0, 0, 0, 0)
def timetz(self): # known case of datetime.datetime.timetz
""" Return time object with same time and tzinfo. """
return time(0, 0)
def tzname(self): # real signature unknown; restored from __doc__
""" Return self.tzinfo.tzname(self). """
pass
@classmethod
def utcfromtimestamp(self, timestamp): # known case of datetime.datetime.utcfromtimestamp
""" timestamp -> UTC datetime from a POSIX timestamp (like time.time()). """
return datetime(1, 1, 1)
@classmethod
def utcnow(cls): # known case of datetime.datetime.utcnow
""" Return a new datetime representing UTC day and time. """
return datetime(1, 1, 1)
def utcoffset(self): # real signature unknown; restored from __doc__
""" Return self.tzinfo.utcoffset(self). """
pass
def utctimetuple(self): # known case of datetime.datetime.utctimetuple
""" Return UTC time tuple, compatible with time.localtime(). """
return (0, 0, 0, 0, 0, 0, 0, 0, 0)
def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __init__(self, year, month, day, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): # real signature unknown; restored from __doc__
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
@staticmethod # known case of __new__
def __new__(cls, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): # known case of datetime.datetime.__new__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __radd__(self, y): # real signature unknown; restored from __doc__
""" x.__radd__(y) <==> y+x """
pass
def __reduce__(self): # real signature unknown; restored from __doc__
""" __reduce__() -> (cls, state) """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
""" x.__sub__(y) <==> x-y """
pass
hour = property(lambda self: 0)
""":type: int"""
microsecond = property(lambda self: 0)
""":type: int"""
minute = property(lambda self: 0)
""":type: int"""
second = property(lambda self: 0)
""":type: int"""
tzinfo = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
max = None # (!) real value is ''
min = None # (!) real value is ''
resolution = None # (!) real value is ''
class time(object):
"""
time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
All arguments are optional. tzinfo may be None, or an instance of
a tzinfo subclass. The remaining arguments may be ints or longs.
"""
def dst(self): # real signature unknown; restored from __doc__
""" Return self.tzinfo.dst(self). """
pass
def isoformat(self): # known case of datetime.time.isoformat
""" Return string in ISO 8601 format, HH:MM:SS[.mmmmmm][+HH:MM]. """
return ""
def replace(self, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): # known case of datetime.time.replace
""" Return time with new specified fields. """
return time(0, 0)
def strftime(self, format): # known case of datetime.time.strftime
""" format -> strftime() style string. """
return ""
def tzname(self): # real signature unknown; restored from __doc__
""" Return self.tzinfo.tzname(self). """
pass
def utcoffset(self): # real signature unknown; restored from __doc__
""" Return self.tzinfo.utcoffset(self). """
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __format__(self, *args, **kwargs): # real signature unknown
""" Formats self with strftime. """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __init__(self, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): # real signature unknown; restored from __doc__
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
@staticmethod # known case of __new__
def __new__(cls, hour=None, minute=None, second=None, microsecond=None, tzinfo=None): # known case of datetime.time.__new__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __nonzero__(self): # real signature unknown; restored from __doc__
""" x.__nonzero__() <==> x != 0 """
pass
def __reduce__(self): # real signature unknown; restored from __doc__
""" __reduce__() -> (cls, state) """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
hour = property(lambda self: 0)
""":type: int"""
microsecond = property(lambda self: 0)
""":type: int"""
minute = property(lambda self: 0)
""":type: int"""
second = property(lambda self: 0)
""":type: int"""
tzinfo = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
max = None # (!) real value is ''
min = None # (!) real value is ''
resolution = None # (!) real value is ''
class timedelta(object):
""" Difference between two datetime values. """
def total_seconds(self, *args, **kwargs): # real signature unknown
""" Total seconds in the duration. """
pass
def __abs__(self): # real signature unknown; restored from __doc__
""" x.__abs__() <==> abs(x) """
pass
def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass
def __div__(self, y): # real signature unknown; restored from __doc__
""" x.__div__(y) <==> x/y """
pass
def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass
def __floordiv__(self, y): # real signature unknown; restored from __doc__
""" x.__floordiv__(y) <==> x//y """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass
def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass
def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass
def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass
def __mul__(self, y): # real signature unknown; restored from __doc__
""" x.__mul__(y) <==> x*y """
pass
def __neg__(self): # real signature unknown; restored from __doc__
""" x.__neg__() <==> -x """
pass
@staticmethod # known case of __new__
def __new__(cls, days=None, seconds=None, microseconds=None, milliseconds=None, minutes=None, hours=None, weeks=None): # known case of datetime.timedelta.__new__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass
def __nonzero__(self): # real signature unknown; restored from __doc__
""" x.__nonzero__() <==> x != 0 """
pass
def __pos__(self): # real signature unknown; restored from __doc__
""" x.__pos__() <==> +x """
pass
def __radd__(self, y): # real signature unknown; restored from __doc__
""" x.__radd__(y) <==> y+x """
pass
def __rdiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rdiv__(y) <==> y/x """
pass
def __reduce__(self): # real signature unknown; restored from __doc__
""" __reduce__() -> (cls, state) """
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __rfloordiv__(self, y): # real signature unknown; restored from __doc__
""" x.__rfloordiv__(y) <==> y//x """
pass
def __rmul__(self, y): # real signature unknown; restored from __doc__
""" x.__rmul__(y) <==> y*x """
pass
def __rsub__(self, y): # real signature unknown; restored from __doc__
""" x.__rsub__(y) <==> y-x """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
def __sub__(self, y): # real signature unknown; restored from __doc__
""" x.__sub__(y) <==> x-y """
pass
days = property(lambda self: 0)
"""Number of days.
:type: int
"""
microseconds = property(lambda self: 0)
"""Number of microseconds (>= 0 and less than 1 second).
:type: int
"""
seconds = property(lambda self: 0)
"""Number of seconds (>= 0 and less than 1 day).
:type: int
"""
max = None # (!) real value is ''
min = None # (!) real value is ''
resolution = None # (!) real value is ''
class tzinfo(object):
""" Abstract base class for time zone info objects. """
def dst(self, date_time): # known case of datetime.tzinfo.dst
""" datetime -> DST offset in minutes east of UTC. """
return 0
def fromutc(self, date_time): # known case of datetime.tzinfo.fromutc
""" datetime in UTC -> datetime in local time. """
return datetime(1, 1, 1)
def tzname(self, date_time): # known case of datetime.tzinfo.tzname
""" datetime -> string name of time zone. """
return ""
def utcoffset(self, date_time): # known case of datetime.tzinfo.utcoffset
""" datetime -> minutes east of UTC (negative for west of UTC). """
return 0
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" -> (cls, state) """
pass
# variables with complex values
datetime_CAPI = None # (!) real value is ''
@@ -0,0 +1,769 @@
# encoding: utf-8
# module exceptions
# from (built-in)
# by generator 1.138
"""
Python's standard exception class hierarchy.
Exceptions found here are defined both in the exceptions module and the
built-in namespace. It is recommended that user-defined exceptions
inherit from Exception. See the documentation for the exception
inheritance hierarchy.
"""
# no imports
# no functions
# classes
class BaseException(object):
""" Common base class for all exceptions """
def __delattr__(self, name): # real signature unknown; restored from __doc__
""" x.__delattr__('name') <==> del x.name """
pass
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) <==> x[i:j]
Use of negative indices is not supported.
"""
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
pass
def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass
def __setattr__(self, name, value): # real signature unknown; restored from __doc__
""" x.__setattr__('name', value) <==> x.name = value """
pass
def __setstate__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
def __unicode__(self): # known case of exceptions.BaseException.__unicode__
# no doc
return u""
args = property(lambda self: tuple())
""":type: tuple"""
message = property(lambda self: '', lambda self, v: None, lambda self: None)
""":type: string"""
__dict__ = None # (!) real value is ''
class Exception(BaseException):
""" Common base class for all non-exit exceptions. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class StandardError(Exception):
"""
Base class for all standard Python exceptions that do not represent
interpreter exiting.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class ArithmeticError(StandardError):
""" Base class for arithmetic errors. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class AssertionError(StandardError):
""" Assertion failed. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class AttributeError(StandardError):
""" Attribute not found. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class BufferError(StandardError):
""" Buffer error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class Warning(Exception):
""" Base class for warning categories. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class BytesWarning(Warning):
"""
Base class for warnings about bytes and buffer related problems, mostly
related to conversion from str or comparing to str.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class DeprecationWarning(Warning):
""" Base class for warnings about deprecated features. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class EnvironmentError(StandardError):
""" Base class for I/O related errors. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
errno = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception errno
:type: int
"""
filename = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception filename
:type: string
"""
strerror = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception strerror
:type: int
"""
class EOFError(StandardError):
""" Read beyond end of file. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class FloatingPointError(ArithmeticError):
""" Floating point operation failed. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class FutureWarning(Warning):
"""
Base class for warnings about constructs that will change semantically
in the future.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class GeneratorExit(BaseException):
""" Request that a generator exit. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class ImportError(StandardError):
""" Import can't find module, or can't find name in module. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class ImportWarning(Warning):
""" Base class for warnings about probable mistakes in module imports """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class SyntaxError(StandardError):
""" Invalid syntax. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
filename = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception filename
:type: string
"""
lineno = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception lineno
:type: int
"""
msg = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception msg
:type: string
"""
offset = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception offset
:type: int
"""
print_file_and_line = property(lambda self: True, lambda self, v: None, lambda self: None)
"""exception print_file_and_line
:type: bool
"""
text = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception text
:type: string
"""
class IndentationError(SyntaxError):
""" Improper indentation. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class LookupError(StandardError):
""" Base class for lookup errors. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class IndexError(LookupError):
""" Sequence index out of range. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class IOError(EnvironmentError):
""" I/O operation failed. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class KeyboardInterrupt(BaseException):
""" Program interrupted by user. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class KeyError(LookupError):
""" Mapping key not found. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
class MemoryError(StandardError):
""" Out of memory. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class NameError(StandardError):
""" Name not found globally. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class RuntimeError(StandardError):
""" Unspecified run-time error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class NotImplementedError(RuntimeError):
""" Method or function hasn't been implemented yet. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class OSError(EnvironmentError):
""" OS system call failed. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class OverflowError(ArithmeticError):
""" Result too large to be represented. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class PendingDeprecationWarning(Warning):
"""
Base class for warnings about features which will be deprecated
in the future.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class ReferenceError(StandardError):
""" Weak ref proxy used after referent went away. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class RuntimeWarning(Warning):
""" Base class for warnings about dubious runtime behavior. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class StopIteration(Exception):
""" Signal the end from iterator.next(). """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class SyntaxWarning(Warning):
""" Base class for warnings about dubious syntax. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class SystemError(StandardError):
"""
Internal error in the Python interpreter.
Please report this to the Python maintainer, along with the traceback,
the Python version, and the hardware/OS platform and version.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class SystemExit(BaseException):
""" Request to exit from the interpreter. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
code = property(lambda self: object(), lambda self, v: None, lambda self: None)
class TabError(IndentationError):
""" Improper mixture of spaces and tabs. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class TypeError(StandardError):
""" Inappropriate argument type. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class UnboundLocalError(NameError):
""" Local name referenced but not bound to a value. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class ValueError(StandardError):
""" Inappropriate argument value (of correct type). """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class UnicodeError(ValueError):
""" Unicode related error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class UnicodeDecodeError(UnicodeError):
""" Unicode decoding error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception encoding"""
end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception end"""
object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception object"""
reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception reason"""
start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception start"""
class UnicodeEncodeError(UnicodeError):
""" Unicode encoding error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
encoding = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception encoding
:type: string
"""
end = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception end
:type: int
"""
object = property(lambda self: object(), lambda self, v: None, lambda self: None)
reason = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception reason
:type: string
"""
start = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception start
:type: int
"""
class UnicodeTranslateError(UnicodeError):
""" Unicode translation error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
def __str__(self): # real signature unknown; restored from __doc__
""" x.__str__() <==> str(x) """
pass
encoding = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception encoding
:type: string
"""
end = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception end
:type: int
"""
object = property(lambda self: object(), lambda self, v: None, lambda self: None)
reason = property(lambda self: '', lambda self, v: None, lambda self: None)
"""exception reason
:type: string
"""
start = property(lambda self: 0, lambda self, v: None, lambda self: None)
"""exception start
:type: int
"""
class UnicodeWarning(Warning):
"""
Base class for warnings about Unicode related problems, mostly
related to conversion problems.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class UserWarning(Warning):
""" Base class for warnings generated by user code. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
class ZeroDivisionError(ArithmeticError):
""" Second argument to a division or modulo operation was zero. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
@@ -0,0 +1,463 @@
# encoding: utf-8
# module sys
# from (built-in)
# by generator 1.138
"""
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules
displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
To customize printing in an interactive session or to install a custom
top-level exception handler, assign other functions to replace these.
exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
Assigning to sys.exitfunc is deprecated; use the atexit module instead.
stdin -- standard input file object; used by raw_input() and input()
stdout -- standard output file object; used by the print statement
stderr -- standard error object; used for error messages
By assigning other file objects (or objects that behave like files)
to these, it is possible to redirect all of the interpreter's I/O.
last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
These three are only available in an interactive session after a
traceback has been printed.
exc_type -- type of exception currently being handled
exc_value -- value of exception currently being handled
exc_traceback -- traceback of exception currently being handled
The function exc_info() should be used instead of these three,
because it is thread-safe.
Static objects:
float_info -- a dict with information about the float inplementation.
long_info -- a struct sequence with information about the long implementation.
maxint -- the largest supported integer (the smallest is -maxint-1)
maxsize -- the largest supported length of containers.
maxunicode -- the largest supported character
builtin_module_names -- tuple of module names built into this interpreter
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
hexversion -- version information encoded as a single integer
copyright -- copyright notice pertaining to this interpreter
platform -- platform identifier
executable -- absolute path of the executable binary of the Python interpreter
prefix -- prefix used to find the Python library
exec_prefix -- prefix used to find the machine-specific Python library
float_repr_style -- string indicating the style of repr() output for floats
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!
Functions:
displayhook() -- print an object to the screen, and save it in __builtin__._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exc_clear() -- clear the exception state for the current thread
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function
"""
# no imports
# Variables with simple values
api_version = 1013
byteorder = 'little'
copyright = 'Copyright (c) 2001-2015 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.'
dont_write_bytecode = True
exc_type = None
executable = '/Users/vlan/.virtualenvs/obraz-py2.7/bin/python'
exec_prefix = '/Users/vlan/.virtualenvs/obraz-py2.7'
float_repr_style = 'short'
hexversion = 34015984
maxint = 9223372036854775807
maxsize = 9223372036854775807
maxunicode = 65535
platform = 'darwin'
prefix = '/Users/vlan/.virtualenvs/obraz-py2.7'
py3kwarning = False
real_prefix = '/System/Library/Frameworks/Python.framework/Versions/2.7'
version = '2.7.10 (default, Oct 23 2015, 18:05:06) \n[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)]'
# functions
def callstats(): # real signature unknown; restored from __doc__
"""
callstats() -> tuple of integers
Return a tuple of function call statistics, if CALL_PROFILE was defined
when Python was built. Otherwise, return None.
When enabled, this function returns detailed, implementation-specific
details about the number of function calls executed. The return value is
a 11-tuple where the entries in the tuple are counts of:
0. all function calls
1. calls to PyFunction_Type objects
2. PyFunction calls that do not create an argument tuple
3. PyFunction calls that do not create an argument tuple
and bypass PyEval_EvalCodeEx()
4. PyMethod calls
5. PyMethod calls on bound methods
6. PyType calls
7. PyCFunction calls
8. generator calls
9. All other calls
10. Number of stack pops performed by call_function()
"""
return ()
def call_tracing(func, args): # real signature unknown; restored from __doc__
"""
call_tracing(func, args) -> object
Call func(*args), while tracing is enabled. The tracing state is
saved, and restored afterwards. This is intended to be called from
a debugger from a checkpoint, to recursively debug some other code.
"""
return object()
def displayhook(p_object): # real signature unknown; restored from __doc__
"""
displayhook(object) -> None
Print an object to sys.stdout and also save it in __builtin__._
"""
pass
def excepthook(exctype, value, traceback): # real signature unknown; restored from __doc__
"""
excepthook(exctype, value, traceback) -> None
Handle an exception by displaying it with a traceback on sys.stderr.
"""
pass
def exc_clear(): # real signature unknown; restored from __doc__
"""
exc_clear() -> None
Clear global information on the current exception. Subsequent calls to
exc_info() will return (None,None,None) until another exception is raised
in the current thread or the execution stack returns to a frame where
another exception is being handled.
"""
pass
def exc_info(): # real signature unknown; restored from __doc__
"""
exc_info() -> (type, value, traceback)
Return information about the most recent exception caught by an except
clause in the current stack frame or in an older stack frame.
"""
pass
def exit(status=None): # real signature unknown; restored from __doc__
"""
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is an integer, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
"""
pass
def exitfunc(): # reliably restored by inspect
"""
run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out.
"""
pass
def getcheckinterval(): # real signature unknown; restored from __doc__
""" getcheckinterval() -> current check interval; see setcheckinterval(). """
pass
def getdefaultencoding(): # real signature unknown; restored from __doc__
"""
getdefaultencoding() -> string
Return the current default string encoding used by the Unicode
implementation.
"""
return ""
def getdlopenflags(): # real signature unknown; restored from __doc__
"""
getdlopenflags() -> int
Return the current value of the flags that are used for dlopen calls.
The flag constants are defined in the ctypes and DLFCN modules.
"""
return 0
def getfilesystemencoding(): # real signature unknown; restored from __doc__
"""
getfilesystemencoding() -> string
Return the encoding used to convert Unicode filenames in
operating system filenames.
"""
return ""
def getprofile(): # real signature unknown; restored from __doc__
"""
getprofile()
Return the profiling function set with sys.setprofile.
See the profiler chapter in the library manual.
"""
pass
def getrecursionlimit(): # real signature unknown; restored from __doc__
"""
getrecursionlimit()
Return the current value of the recursion limit, the maximum depth
of the Python interpreter stack. This limit prevents infinite
recursion from causing an overflow of the C stack and crashing Python.
"""
pass
def getrefcount(p_object): # real signature unknown; restored from __doc__
"""
getrefcount(object) -> integer
Return the reference count of object. The count returned is generally
one higher than you might expect, because it includes the (temporary)
reference as an argument to getrefcount().
"""
return 0
def getsizeof(p_object, default): # real signature unknown; restored from __doc__
"""
getsizeof(object, default) -> int
Return the size of object in bytes.
"""
return 0
def gettrace(): # real signature unknown; restored from __doc__
"""
gettrace()
Return the global debug tracing function set with sys.settrace.
See the debugger chapter in the library manual.
"""
pass
def setcheckinterval(n): # real signature unknown; restored from __doc__
"""
setcheckinterval(n)
Tell the Python interpreter to check for asynchronous events every
n instructions. This also affects how often thread switches occur.
"""
pass
def setdlopenflags(n): # real signature unknown; restored from __doc__
"""
setdlopenflags(n) -> None
Set the flags used by the interpreter for dlopen calls, such as when the
interpreter loads extension modules. Among other things, this will enable
a lazy resolving of symbols when importing a module, if called as
sys.setdlopenflags(0). To share symbols across extension modules, call as
sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules
can be either found in the ctypes module, or in the DLFCN module. If DLFCN
is not available, it can be generated from /usr/include/dlfcn.h using the
h2py script.
"""
pass
def setprofile(function): # real signature unknown; restored from __doc__
"""
setprofile(function)
Set the profiling function. It will be called on each function call
and return. See the profiler chapter in the library manual.
"""
pass
def setrecursionlimit(n): # real signature unknown; restored from __doc__
"""
setrecursionlimit(n)
Set the maximum depth of the Python interpreter stack to n. This
limit prevents infinite recursion from causing an overflow of the C
stack and crashing Python. The highest possible limit is platform-
dependent.
"""
pass
def settrace(function): # real signature unknown; restored from __doc__
"""
settrace(function)
Set the global debug tracing function. It will be called on each
function call. See the debugger chapter in the library manual.
"""
pass
def _clear_type_cache(): # real signature unknown; restored from __doc__
"""
_clear_type_cache() -> None
Clear the internal type lookup cache.
"""
pass
def _current_frames(): # real signature unknown; restored from __doc__
"""
_current_frames() -> dictionary
Return a dictionary mapping each current thread T's thread id to T's
current stack frame.
This function should be used for specialized purposes only.
"""
return {}
def _getframe(depth=None): # real signature unknown; restored from __doc__
"""
_getframe([depth]) -> frameobject
Return a frame object from the call stack. If optional integer depth is
given, return the frame object that many calls below the top of the stack.
If that is deeper than the call stack, ValueError is raised. The default
for depth is zero, returning the frame at the top of the call stack.
This function should be used for internal and specialized
purposes only.
"""
pass
def __displayhook__(*args, **kwargs): # real signature unknown
"""
displayhook(object) -> None
Print an object to sys.stdout and also save it in __builtin__._
"""
pass
def __excepthook__(*args, **kwargs): # real signature unknown
"""
excepthook(exctype, value, traceback) -> None
Handle an exception by displaying it with a traceback on sys.stderr.
"""
pass
# no classes
# variables with complex values
argv = [] # real value of type <type 'list'> skipped
builtin_module_names = () # real value of type <type 'tuple'> skipped
flags = None # (!) real value is ''
float_info = None # (!) real value is ''
long_info = None # (!) real value is ''
meta_path = []
modules = {} # real value of type <type 'dict'> skipped
path = [
'/Users/vlan/src/idea/out/classes/production/python-helpers',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python27.zip',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/plat-darwin',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/plat-mac',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/vlan/.virtualenvs/obraz-py2.7/Extras/lib/python',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/lib-tk',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/lib-old',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/Users/vlan/.virtualenvs/obraz-py2.7/lib/python2.7/site-packages',
]
path_hooks = [
None, # (!) real value is ''
]
path_importer_cache = {} # real value of type <type 'dict'> skipped
stderr = open('') # real value of type <type 'file'> replaced
stdin = open('') # real value of type <type 'file'> replaced
stdout = open('') # real value of type <type 'file'> replaced
subversion = (
'CPython',
'',
'',
)
version_info = None # (!) real value is ''
warnoptions = []
_mercurial = (
'CPython',
'',
'',
)
__stderr__ = None # (!) real value is ''
__stdin__ = None # (!) real value is ''
__stdout__ = stdout
# intermittent names
exc_value = Exception()
exc_traceback=None
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
from _collections_abc import *
from _collections_abc import __all__
File diff suppressed because it is too large Load Diff
+99
View File
@@ -0,0 +1,99 @@
"""The io module provides the Python interfaces to stream handling. The
builtin open function is defined in this module.
At the top of the I/O hierarchy is the abstract base class IOBase. It
defines the basic interface to a stream. Note, however, that there is no
separation between reading and writing to streams; implementations are
allowed to raise an OSError if they do not support a given operation.
Extending IOBase is RawIOBase which deals simply with the reading and
writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide
an interface to OS files.
BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its
subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer
streams that are readable, writable, and both respectively.
BufferedRandom provides a buffered interface to random access
streams. BytesIO is a simple stream of in-memory bytes.
Another IOBase subclass, TextIOBase, deals with the encoding and decoding
of streams into text. TextIOWrapper, which extends it, is a buffered text
interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO
is an in-memory stream for text.
Argument names are not part of the specification, and only the arguments
of open() are intended to be used as keyword arguments.
data:
DEFAULT_BUFFER_SIZE
An int containing the default buffer size used by the module's buffered
I/O classes. open() uses the file's blksize (as obtained by os.stat) if
possible.
"""
# New I/O library conforming to PEP 3116.
__author__ = ("Guido van Rossum <guido@python.org>, "
"Mike Verdone <mike.verdone@gmail.com>, "
"Mark Russell <mark.russell@zen.co.uk>, "
"Antoine Pitrou <solipsis@pitrou.net>, "
"Amaury Forgeot d'Arc <amauryfa@gmail.com>, "
"Benjamin Peterson <benjamin@python.org>")
__all__ = ["BlockingIOError", "open", "IOBase", "RawIOBase", "FileIO",
"BytesIO", "StringIO", "BufferedIOBase",
"BufferedReader", "BufferedWriter", "BufferedRWPair",
"BufferedRandom", "TextIOBase", "TextIOWrapper",
"UnsupportedOperation", "SEEK_SET", "SEEK_CUR", "SEEK_END"]
import _io
import abc
from _io import (DEFAULT_BUFFER_SIZE, BlockingIOError, UnsupportedOperation,
open, FileIO, BytesIO, StringIO, BufferedReader,
BufferedWriter, BufferedRWPair, BufferedRandom,
IncrementalNewlineDecoder, TextIOWrapper)
OpenWrapper = _io.open # for compatibility with _pyio
# Pretend this exception was created here.
UnsupportedOperation.__module__ = "io"
# for seek()
SEEK_SET = 0
SEEK_CUR = 1
SEEK_END = 2
# Declaring ABCs in C is tricky so we do it here.
# Method descriptions and default implementations are inherited from the C
# version however.
class IOBase(_io._IOBase, metaclass=abc.ABCMeta):
__doc__ = _io._IOBase.__doc__
class RawIOBase(_io._RawIOBase, IOBase):
__doc__ = _io._RawIOBase.__doc__
class BufferedIOBase(_io._BufferedIOBase, IOBase):
__doc__ = _io._BufferedIOBase.__doc__
class TextIOBase(_io._TextIOBase, IOBase):
__doc__ = _io._TextIOBase.__doc__
RawIOBase.register(FileIO)
for klass in (BytesIO, BufferedReader, BufferedWriter, BufferedRandom,
BufferedRWPair):
BufferedIOBase.register(klass)
for klass in (StringIO, TextIOWrapper):
TextIOBase.register(klass)
del klass
try:
from _io import _WindowsConsoleIO
except ImportError:
pass
else:
RawIOBase.register(_WindowsConsoleIO)
+366
View File
@@ -0,0 +1,366 @@
#
# Secret Labs' Regular Expression Engine
#
# re-compatible interface for the sre matching engine
#
# Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
#
# This version of the SRE library can be redistributed under CNRI's
# Python 1.6 license. For any other use, please contact Secret Labs
# AB (info@pythonware.com).
#
# Portions of this engine have been developed in cooperation with
# CNRI. Hewlett-Packard provided funding for 1.6 integration and
# other compatibility work.
#
r"""Support for regular expressions (RE).
This module provides regular expression matching operations similar to
those found in Perl. It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.
Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like "A", "a", or "0", are the simplest
regular expressions; they simply match themselves. You can
concatenate ordinary characters, so last matches the string 'last'.
The special characters are:
"." Matches any character except a newline.
"^" Matches the start of the string.
"$" Matches the end of the string or just before the newline at
the end of the string.
"*" Matches 0 or more (greedy) repetitions of the preceding RE.
Greedy means that it will match as many repetitions as possible.
"+" Matches 1 or more (greedy) repetitions of the preceding RE.
"?" Matches 0 or 1 (greedy) of the preceding RE.
*?,+?,?? Non-greedy versions of the previous three special characters.
{m,n} Matches from m to n repetitions of the preceding RE.
{m,n}? Non-greedy version of the above.
"\\" Either escapes special characters or signals a special sequence.
[] Indicates a set of characters.
A "^" as the first character indicates a complementing set.
"|" A|B, creates an RE that will match either A or B.
(...) Matches the RE inside the parentheses.
The contents can be retrieved or matched later in the string.
(?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).
(?:...) Non-grouping version of regular parentheses.
(?P<name>...) The substring matched by the group is accessible by name.
(?P=name) Matches the text matched earlier by the group named name.
(?#...) A comment; ignored.
(?=...) Matches if ... matches next, but doesn't consume the string.
(?!...) Matches if ... doesn't match next.
(?<=...) Matches if preceded by ... (must be fixed length).
(?<!...) Matches if not preceded by ... (must be fixed length).
(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
the (optional) no pattern otherwise.
The special sequences consist of "\\" and a character from the list
below. If the ordinary character is not on the list, then the
resulting RE will match the second character.
\number Matches the contents of the group of the same number.
\A Matches only at the start of the string.
\Z Matches only at the end of the string.
\b Matches the empty string, but only at the start or end of a word.
\B Matches the empty string, but not at the start or end of a word.
\d Matches any decimal digit; equivalent to the set [0-9] in
bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the whole
range of Unicode digits.
\D Matches any non-digit character; equivalent to [^\d].
\s Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the whole
range of Unicode whitespace characters.
\S Matches any non-whitespace character; equivalent to [^\s].
\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
in bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the
range of Unicode alphanumeric characters (letters plus digits
plus underscore).
With LOCALE, it will match the set [0-9_] plus characters defined
as letters for the current locale.
\W Matches the complement of \w.
\\ Matches a literal backslash.
This module exports the following functions:
match Match a regular expression pattern to the beginning of a string.
fullmatch Match a regular expression pattern to all of a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a Match object for each match.
compile Compile a pattern into a Pattern object.
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
Some of the functions in this module takes flags as optional parameters:
A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
match the corresponding ASCII character categories
(rather than the whole Unicode categories, which is the
default).
For bytes patterns, this flag is the only available
behaviour and needn't be specified.
I IGNORECASE Perform case-insensitive matching.
L LOCALE Make \w, \W, \b, \B, dependent on the current locale.
M MULTILINE "^" matches the beginning of lines (after a newline)
as well as the string.
"$" matches the end of lines (before a newline) as well
as the end of the string.
S DOTALL "." matches any character at all, including the newline.
X VERBOSE Ignore whitespace and comments for nicer looking RE's.
U UNICODE For compatibility only. Ignored for string patterns (it
is the default), and forbidden for bytes patterns.
This module also defines an exception 'error'.
"""
import enum
import sre_compile
import sre_parse
import functools
try:
import _locale
except ImportError:
_locale = None
# public symbols
__all__ = [
"match", "fullmatch", "search", "sub", "subn", "split",
"findall", "finditer", "compile", "purge", "template", "escape",
"error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U",
"ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",
"UNICODE",
]
__version__ = "2.2.1"
class RegexFlag(enum.IntFlag):
ASCII = sre_compile.SRE_FLAG_ASCII # assume ascii "locale"
IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case
LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale
UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale"
MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline
DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline
VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments
A = ASCII
I = IGNORECASE
L = LOCALE
U = UNICODE
M = MULTILINE
S = DOTALL
X = VERBOSE
# sre extensions (experimental, don't rely on these)
TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking
T = TEMPLATE
DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation
globals().update(RegexFlag.__members__)
# sre exception
error = sre_compile.error
# --------------------------------------------------------------------
# public interface
def match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a Match object, or None if no match was found."""
return _compile(pattern, flags).match(string)
def fullmatch(pattern, string, flags=0):
"""Try to apply the pattern to all of the string, returning
a Match object, or None if no match was found."""
return _compile(pattern, flags).fullmatch(string)
def search(pattern, string, flags=0):
"""Scan through string looking for a match to the pattern, returning
a Match object, or None if no match was found."""
return _compile(pattern, flags).search(string)
def sub(pattern, repl, string, count=0, flags=0):
"""Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a string, backslash escapes in it are processed. If it is
a callable, it's passed the Match object and must return
a replacement string to be used."""
return _compile(pattern, flags).sub(repl, string, count)
def subn(pattern, repl, string, count=0, flags=0):
"""Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if a string, backslash escapes in it are processed.
If it is a callable, it's passed the Match object and must
return a replacement string to be used."""
return _compile(pattern, flags).subn(repl, string, count)
def split(pattern, string, maxsplit=0, flags=0):
"""Split the source string by the occurrences of the pattern,
returning a list containing the resulting substrings. If
capturing parentheses are used in pattern, then the text of all
groups in the pattern are also returned as part of the resulting
list. If maxsplit is nonzero, at most maxsplit splits occur,
and the remainder of the string is returned as the final element
of the list."""
return _compile(pattern, flags).split(string, maxsplit)
def findall(pattern, string, flags=0):
"""Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result."""
return _compile(pattern, flags).findall(string)
def finditer(pattern, string, flags=0):
"""Return an iterator over all non-overlapping matches in the
string. For each match, the iterator returns a Match object.
Empty matches are included in the result."""
return _compile(pattern, flags).finditer(string)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a Pattern object."
return _compile(pattern, flags)
def purge():
"Clear the regular expression caches"
_cache.clear()
_compile_repl.cache_clear()
def template(pattern, flags=0):
"Compile a template pattern, returning a Pattern object"
return _compile(pattern, flags|T)
# SPECIAL_CHARS
# closing ')', '}' and ']'
# '-' (a range in character set)
# '&', '~', (extended character set operations)
# '#' (comment) and WHITESPACE (ignored) in verbose mode
_special_chars_map = {i: '\\' + chr(i) for i in b'()[]{}?*+-|^$\\.&~# \t\n\r\v\f'}
def escape(pattern):
"""
Escape special characters in a string.
"""
if isinstance(pattern, str):
return pattern.translate(_special_chars_map)
else:
pattern = str(pattern, 'latin1')
return pattern.translate(_special_chars_map).encode('latin1')
Pattern = type(sre_compile.compile('', 0))
Match = type(sre_compile.compile('', 0).match(''))
# --------------------------------------------------------------------
# internals
_cache = {} # ordered!
_MAXCACHE = 512
def _compile(pattern, flags):
# internal: compile pattern
if isinstance(flags, RegexFlag):
flags = flags.value
try:
return _cache[type(pattern), pattern, flags]
except KeyError:
pass
if isinstance(pattern, Pattern):
if flags:
raise ValueError(
"cannot process flags argument with a compiled pattern")
return pattern
if not sre_compile.isstring(pattern):
raise TypeError("first argument must be string or compiled pattern")
p = sre_compile.compile(pattern, flags)
if not (flags & DEBUG):
if len(_cache) >= _MAXCACHE:
# Drop the oldest item
try:
del _cache[next(iter(_cache))]
except (StopIteration, RuntimeError, KeyError):
pass
_cache[type(pattern), pattern, flags] = p
return p
@functools.lru_cache(_MAXCACHE)
def _compile_repl(repl, pattern):
# internal: compile replacement pattern
return sre_parse.parse_template(repl, pattern)
def _expand(pattern, match, template):
# internal: Match.expand implementation hook
template = sre_parse.parse_template(template, pattern)
return sre_parse.expand_template(template, match)
def _subx(pattern, template):
# internal: Pattern.sub/subn implementation helper
template = _compile_repl(template, pattern)
if not template[0] and len(template[1]) == 1:
# literal replacement
return template[1][0]
def filter(match, template=template):
return sre_parse.expand_template(template, match)
return filter
# register myself for pickling
import copyreg
def _pickle(p):
return _compile, (p.pattern, p.flags)
copyreg.pickle(Pattern, _pickle, _compile)
# --------------------------------------------------------------------
# experimental stuff (see python-dev discussions for details)
class Scanner:
def __init__(self, lexicon, flags=0):
from sre_constants import BRANCH, SUBPATTERN
if isinstance(flags, RegexFlag):
flags = flags.value
self.lexicon = lexicon
# combine phrases into a compound pattern
p = []
s = sre_parse.Pattern()
s.flags = flags
for phrase, action in lexicon:
gid = s.opengroup()
p.append(sre_parse.SubPattern(s, [
(SUBPATTERN, (gid, 0, 0, sre_parse.parse(phrase, flags))),
]))
s.closegroup(gid, p[-1])
p = sre_parse.SubPattern(s, [(BRANCH, (None, p))])
self.scanner = sre_compile.compile(p)
def scan(self, string):
result = []
append = result.append
match = self.scanner.scanner(string).match
i = 0
while True:
m = match()
if not m:
break
j = m.end()
if i == j:
break
action = self.lexicon[m.lastindex-1][1]
if callable(action):
self.match = m
action = action(self, m.group())
if action is not None:
append(action)
i = j
return result, string[i:]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,704 @@
# encoding: utf-8
# module sys
# from (built-in)
# by generator 1.145
"""
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules
displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
To customize printing in an interactive session or to install a custom
top-level exception handler, assign other functions to replace these.
stdin -- standard input file object; used by input()
stdout -- standard output file object; used by print()
stderr -- standard error object; used for error messages
By assigning other file objects (or objects that behave like files)
to these, it is possible to redirect all of the interpreter's I/O.
last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
These three are only available in an interactive session after a
traceback has been printed.
Static objects:
builtin_module_names -- tuple of module names built into this interpreter
copyright -- copyright notice pertaining to this interpreter
exec_prefix -- prefix used to find the machine-specific Python library
executable -- absolute path of the executable binary of the Python interpreter
float_info -- a struct sequence with information about the float implementation.
float_repr_style -- string indicating the style of repr() output for floats
hash_info -- a struct sequence with information about the hash algorithm.
hexversion -- version information encoded as a single integer
implementation -- Python implementation information.
int_info -- a struct sequence with information about the int implementation.
maxsize -- the largest supported length of containers.
maxunicode -- the value of the largest Unicode code point
platform -- platform identifier
prefix -- prefix used to find the Python library
thread_info -- a struct sequence with information about the thread implementation.
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
dllhandle -- [Windows only] integer handle of the Python DLL
winver -- [Windows only] version number of the Python DLL
_enablelegacywindowsfsencoding -- [Windows only]
__stdin__ -- the original stdin; don't touch!
__stdout__ -- the original stdout; don't touch!
__stderr__ -- the original stderr; don't touch!
__displayhook__ -- the original displayhook; don't touch!
__excepthook__ -- the original excepthook; don't touch!
Functions:
displayhook() -- print an object to the screen, and save it in builtins._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function
"""
# no imports
# Variables with simple values
api_version = 1013
base_exec_prefix = 'C:\\Python37'
base_prefix = 'C:\\Python37'
byteorder = 'little'
copyright = 'Copyright (c) 2001-2018 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.'
dllhandle = 140705079492608
dont_write_bytecode = True
executable = 'C:\\Python37\\python.exe'
exec_prefix = 'C:\\Python37'
float_repr_style = 'short'
hexversion = 50790896
maxsize = 9223372036854775807
maxunicode = 1114111
platform = 'win32'
prefix = 'C:\\Python37'
version = '3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)]'
winver = '3.7'
_framework = ''
_home = None
# functions
def breakpointhook(*args, **kws): # real signature unknown; restored from __doc__
"""
breakpointhook(*args, **kws)
This hook function is called by built-in breakpoint().
"""
pass
def callstats(): # real signature unknown; restored from __doc__
"""
callstats() -> tuple of integers
Return a tuple of function call statistics, if CALL_PROFILE was defined
when Python was built. Otherwise, return None.
When enabled, this function returns detailed, implementation-specific
details about the number of function calls executed. The return value is
a 11-tuple where the entries in the tuple are counts of:
0. all function calls
1. calls to PyFunction_Type objects
2. PyFunction calls that do not create an argument tuple
3. PyFunction calls that do not create an argument tuple
and bypass PyEval_EvalCodeEx()
4. PyMethod calls
5. PyMethod calls on bound methods
6. PyType calls
7. PyCFunction calls
8. generator calls
9. All other calls
10. Number of stack pops performed by call_function()
"""
return ()
def call_tracing(func, args): # real signature unknown; restored from __doc__
"""
call_tracing(func, args) -> object
Call func(*args), while tracing is enabled. The tracing state is
saved, and restored afterwards. This is intended to be called from
a debugger from a checkpoint, to recursively debug some other code.
"""
return object()
def displayhook(p_object): # real signature unknown; restored from __doc__
"""
displayhook(object) -> None
Print an object to sys.stdout and also save it in builtins._
"""
pass
def excepthook(exctype, value, traceback): # real signature unknown; restored from __doc__
"""
excepthook(exctype, value, traceback) -> None
Handle an exception by displaying it with a traceback on sys.stderr.
"""
pass
def exc_info(): # real signature unknown; restored from __doc__
"""
exc_info() -> (type, value, traceback)
Return information about the most recent exception caught by an except
clause in the current stack frame or in an older stack frame.
"""
pass
def exit(status=None): # real signature unknown; restored from __doc__
"""
exit([status])
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is an integer, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).
"""
pass
def getallocatedblocks(): # real signature unknown; restored from __doc__
"""
getallocatedblocks() -> integer
Return the number of memory blocks currently allocated, regardless of their
size.
"""
return 0
def getcheckinterval(): # real signature unknown; restored from __doc__
""" getcheckinterval() -> current check interval; see setcheckinterval(). """
pass
def getdefaultencoding(): # real signature unknown; restored from __doc__
"""
getdefaultencoding() -> string
Return the current default string encoding used by the Unicode
implementation.
"""
return ""
def getfilesystemencodeerrors(): # real signature unknown; restored from __doc__
"""
getfilesystemencodeerrors() -> string
Return the error mode used to convert Unicode filenames in
operating system filenames.
"""
return ""
def getfilesystemencoding(): # real signature unknown; restored from __doc__
"""
getfilesystemencoding() -> string
Return the encoding used to convert Unicode filenames in
operating system filenames.
"""
return ""
def getprofile(): # real signature unknown; restored from __doc__
"""
getprofile()
Return the profiling function set with sys.setprofile.
See the profiler chapter in the library manual.
"""
pass
def getrecursionlimit(): # real signature unknown; restored from __doc__
"""
getrecursionlimit()
Return the current value of the recursion limit, the maximum depth
of the Python interpreter stack. This limit prevents infinite
recursion from causing an overflow of the C stack and crashing Python.
"""
pass
def getrefcount(p_object): # real signature unknown; restored from __doc__
"""
getrefcount(object) -> integer
Return the reference count of object. The count returned is generally
one higher than you might expect, because it includes the (temporary)
reference as an argument to getrefcount().
"""
return 0
def getsizeof(p_object, default): # real signature unknown; restored from __doc__
"""
getsizeof(object, default) -> int
Return the size of object in bytes.
"""
return 0
def getswitchinterval(): # real signature unknown; restored from __doc__
""" getswitchinterval() -> current thread switch interval; see setswitchinterval(). """
pass
def gettrace(): # real signature unknown; restored from __doc__
"""
gettrace()
Return the global debug tracing function set with sys.settrace.
See the debugger chapter in the library manual.
"""
pass
def getwindowsversion(): # real signature unknown; restored from __doc__
"""
getwindowsversion()
Return information about the running version of Windows as a named tuple.
The members are named: major, minor, build, platform, service_pack,
service_pack_major, service_pack_minor, suite_mask, and product_type. For
backward compatibility, only the first 5 items are available by indexing.
All elements are numbers, except service_pack and platform_type which are
strings, and platform_version which is a 3-tuple. Platform is always 2.
Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a
server. Platform_version is a 3-tuple containing a version number that is
intended for identifying the OS rather than feature detection.
"""
pass
def get_asyncgen_hooks(): # real signature unknown; restored from __doc__
"""
get_asyncgen_hooks()
Return a namedtuple of installed asynchronous generators hooks (firstiter, finalizer).
"""
pass
def get_coroutine_origin_tracking_depth(*args, **kwargs): # real signature unknown
""" Check status of origin tracking for coroutine objects in this thread. """
pass
def get_coroutine_wrapper(): # real signature unknown; restored from __doc__
"""
get_coroutine_wrapper()
Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper.
"""
pass
def intern(string): # real signature unknown; restored from __doc__
"""
intern(string) -> string
``Intern'' the given string. This enters the string in the (global)
table of interned strings whose purpose is to speed up dictionary lookups.
Return the string itself or the previously interned string object with the
same value.
"""
return ""
def is_finalizing(): # real signature unknown; restored from __doc__
"""
is_finalizing()
Return True if Python is exiting.
"""
pass
def setcheckinterval(n): # real signature unknown; restored from __doc__
"""
setcheckinterval(n)
Tell the Python interpreter to check for asynchronous events every
n instructions. This also affects how often thread switches occur.
"""
pass
def setprofile(function): # real signature unknown; restored from __doc__
"""
setprofile(function)
Set the profiling function. It will be called on each function call
and return. See the profiler chapter in the library manual.
"""
pass
def setrecursionlimit(n): # real signature unknown; restored from __doc__
"""
setrecursionlimit(n)
Set the maximum depth of the Python interpreter stack to n. This
limit prevents infinite recursion from causing an overflow of the C
stack and crashing Python. The highest possible limit is platform-
dependent.
"""
pass
def setswitchinterval(n): # real signature unknown; restored from __doc__
"""
setswitchinterval(n)
Set the ideal thread switching delay inside the Python interpreter
The actual frequency of switching threads can be lower if the
interpreter executes long sequences of uninterruptible code
(this is implementation-specific and workload-dependent).
The parameter must represent the desired switching delay in seconds
A typical value is 0.005 (5 milliseconds).
"""
pass
def settrace(function): # real signature unknown; restored from __doc__
"""
settrace(function)
Set the global debug tracing function. It will be called on each
function call. See the debugger chapter in the library manual.
"""
pass
def set_asyncgen_hooks(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
set_asyncgen_hooks(*, firstiter=None, finalizer=None)
Set a finalizer for async generators objects.
"""
pass
def set_coroutine_origin_tracking_depth(*args, **kwargs): # real signature unknown
"""
Enable or disable origin tracking for coroutine objects in this thread.
Coroutine objects will track 'depth' frames of traceback information about
where they came from, available in their cr_origin attribute. Set depth of 0
to disable.
"""
pass
def set_coroutine_wrapper(wrapper): # real signature unknown; restored from __doc__
"""
set_coroutine_wrapper(wrapper)
Set a wrapper for coroutine objects.
"""
pass
def _clear_type_cache(): # real signature unknown; restored from __doc__
"""
_clear_type_cache() -> None
Clear the internal type lookup cache.
"""
pass
def _current_frames(): # real signature unknown; restored from __doc__
"""
_current_frames() -> dictionary
Return a dictionary mapping each current thread T's thread id to T's
current stack frame.
This function should be used for specialized purposes only.
"""
return {}
def _debugmallocstats(): # real signature unknown; restored from __doc__
"""
_debugmallocstats()
Print summary info to stderr about the state of
pymalloc's structures.
In Py_DEBUG mode, also perform some expensive internal consistency
checks.
"""
pass
def _enablelegacywindowsfsencoding(): # real signature unknown; restored from __doc__
"""
_enablelegacywindowsfsencoding()
Changes the default filesystem encoding to mbcs:replace for consistency
with earlier versions of Python. See PEP 529 for more information.
This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
environment variable before launching Python.
"""
pass
def _getframe(depth=None): # real signature unknown; restored from __doc__
"""
_getframe([depth]) -> frameobject
Return a frame object from the call stack. If optional integer depth is
given, return the frame object that many calls below the top of the stack.
If that is deeper than the call stack, ValueError is raised. The default
for depth is zero, returning the frame at the top of the call stack.
This function should be used for internal and specialized
purposes only.
"""
pass
def __breakpointhook__(*args, **kwargs): # real signature unknown
"""
breakpointhook(*args, **kws)
This hook function is called by built-in breakpoint().
"""
pass
def __displayhook__(*args, **kwargs): # real signature unknown
"""
displayhook(object) -> None
Print an object to sys.stdout and also save it in builtins._
"""
pass
def __excepthook__(*args, **kwargs): # real signature unknown
"""
excepthook(exctype, value, traceback) -> None
Handle an exception by displaying it with a traceback on sys.stderr.
"""
pass
def __interactivehook__(): # reliably restored by inspect
# no doc
pass
# classes
class __loader__(object):
"""
Meta path import for built-in modules.
All methods are either class or static methods to avoid the need to
instantiate the class.
"""
@classmethod
def create_module(cls, *args, **kwargs): # real signature unknown
""" Create a built-in module """
pass
@classmethod
def exec_module(cls, *args, **kwargs): # real signature unknown
""" Exec a built-in module """
pass
@classmethod
def find_module(cls, *args, **kwargs): # real signature unknown
"""
Find the built-in module.
If 'path' is ever specified then the search is considered a failure.
This method is deprecated. Use find_spec() instead.
"""
pass
@classmethod
def find_spec(cls, *args, **kwargs): # real signature unknown
pass
@classmethod
def get_code(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have code objects. """
pass
@classmethod
def get_source(cls, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have source code. """
pass
@classmethod
def is_package(cls, *args, **kwargs): # real signature unknown
""" Return False as built-in modules are never packages. """
pass
@classmethod
def load_module(cls, *args, **kwargs): # real signature unknown
"""
Load the specified module into sys.modules and return it.
This method is deprecated. Use loader.exec_module instead.
"""
pass
def module_repr(module): # reliably restored by inspect
"""
Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
# variables with complex values
argv = [] # real value of type <class 'list'> skipped
builtin_module_names = () # real value of type <class 'tuple'> skipped
flags = (
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
1,
0,
False,
0,
)
float_info = (
1.7976931348623157e+308,
1024,
308,
2.2250738585072014e-308,
-1021,
-307,
15,
53,
2.220446049250313e-16,
2,
1,
)
hash_info = (
64,
2305843009213693951,
314159,
0,
1000003,
'siphash24',
64,
128,
0,
)
implementation = None # (!) real value is ''
int_info = (
30,
4,
)
meta_path = [
__loader__,
None, # (!) real value is ''
None, # (!) real value is ''
]
modules = {} # real value of type <class 'dict'> skipped
path = [
'C:\\Projects\\IDEA\\out\\classes\\production\\intellij.python.helpers',
'C:\\Python37\\python37.zip',
'C:\\Python37\\DLLs',
'C:\\Python37\\lib',
'C:\\Python37',
'C:\\Python37\\lib\\site-packages',
]
path_hooks = [
None, # (!) real value is ''
None, # (!) real value is ''
]
path_importer_cache = {} # real value of type <class 'dict'> skipped
stderr = None # (!) real value is ''
stdin = None # (!) forward: __stdin__, real value is ''
stdout = None # (!) forward: __stdout__, real value is ''
thread_info = (
'nt',
None,
None,
)
version_info = (
3,
7,
1,
'final',
0,
)
warnoptions = []
_git = (
'CPython',
'v3.7.1',
'260ec2c36a',
)
_xoptions = {}
__spec__ = None # (!) real value is ''
__stderr__ = stderr
__stdin__ = None # (!) real value is ''
__stdout__ = None # (!) real value is ''
# intermittent names
exc_value = Exception()
exc_traceback=None
@@ -88,7 +88,7 @@ def f<error descr="'(' expected">:</error>
pass
# PY-30335
with open('file', <weak_warning descr="Argument equals to default parameter value">'r'</weak_warning>) as file:
with open('file', <weak_warning descr="Argument equals to default parameter value">None</weak_warning>) as file:
pass
# PY-29731
@@ -0,0 +1,5 @@
import logging
logger = logging.getLogger()
logger.exception(<warning descr="Parameter 'msg' unfilled">)</warning>
logging.exception(<warning descr="Parameter 'msg' unfilled">)</warning>
@@ -0,0 +1,9 @@
def getLogger():
pass
def exception(msg):
pass
class Logger(object):
def exception(self, msg):
pass
@@ -0,0 +1,4 @@
import logging
logger = logging.getLogger()
logger.<warning descr="Unresolved attribute reference 'foobar' for class 'Logger'">foobar</warning>()
@@ -0,0 +1,6 @@
def getLogger():
pass
class Logger(object):
def exception(self, msg):
pass
@@ -32,16 +32,7 @@ import static com.jetbrains.python.codeInsight.imports.AddImportHelper.ImportPri
*/
public class PyAddImportTest extends PyTestCase {
public void testAddBuiltin() {
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doAddImport("re", BUILTIN)
)
);
doAddImport("re", BUILTIN);
}
// PY-7400
@@ -61,16 +52,7 @@ public class PyAddImportTest extends PyTestCase {
// PY-14765
public void testNewLastImportInBuiltinGroup() {
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doAddImportWithResolveInProject("sys", BUILTIN)
)
);
doAddImportWithResolveInProject("sys", BUILTIN);
}
// PY-14765
@@ -125,15 +107,9 @@ public class PyAddImportTest extends PyTestCase {
// PY-16373
public void testLocalImportQuickFixAvailable() {
runWithAdditionalFileInLibDir(
"sys.py",
"path = 10",
(__) -> {
myFixture.configureByFile(getTestName(true) + ".py");
myFixture.enableInspections(PyUnresolvedReferencesInspection.class);
assertNotNull(myFixture.findSingleIntention("Import 'sys' locally"));
}
);
myFixture.configureByFile(getTestName(true) + ".py");
myFixture.enableInspections(PyUnresolvedReferencesInspection.class);
assertNotNull(myFixture.findSingleIntention("Import 'sys' locally"));
}
// PY-23475
@@ -41,11 +41,11 @@ public class PyClassNameCompletionTest extends PyTestCase {
}
public void testModule() {
runWithAdditionalFileInLibDir("collections.py", "", (__) -> doTest());
doTest();
}
public void testVariable() {
runWithAdditionalFileInLibDir("datetime.py", "MAXYEAR = 10", (__) -> doTest());
doTest();
}
public void testSubmodule() { // PY-7887
@@ -108,11 +108,7 @@ public class PyClassNameCompletionTest extends PyTestCase {
// PY-20976
public void testOrderingLocalBeforeStdlib() {
runWithAdditionalFileInLibDir(
"sys.py",
"path = 10",
(__) -> doTestCompletionOrder("local_pkg.path", "local_pkg.local_module.path", "sys.path")
);
doTestCompletionOrder("local_pkg.path", "local_pkg.local_module.path", "sys.path");
}
// PY-20976
@@ -142,11 +138,7 @@ public class PyClassNameCompletionTest extends PyTestCase {
// PY-20976
public void testCombinedOrdering() {
runWithAdditionalFileInLibDir(
"sys.py",
"path = 10",
(__) -> doTestCompletionOrder("main.path", "first.foo.path", "sys.path", "_second.bar.path")
);
doTestCompletionOrder("main.path", "first.foo.path", "sys.path", "_second.bar.path");
}
// PY-20976
@@ -7,6 +7,8 @@ import com.jetbrains.python.codeInsight.typing.PyTypeShed
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil.getUserSkeletonsDirectory
import com.jetbrains.python.debugger.PyLineBreakpointType
import com.jetbrains.python.fixtures.PyTestCase
import com.jetbrains.python.sdk.PythonSdkUtil
import com.jetbrains.python.sdk.PythonSdkUtil.findSkeletonsDir
class PyLineBreakpointTypeTest : PyTestCase() {
@@ -25,15 +27,16 @@ class PyLineBreakpointTypeTest : PyTestCase() {
// PY-16932
fun testPutAtSkeleton() {
runWithAdditionalFileInSkeletonDir("my_mod.py", "class A:\n def method(self):\n print(\"ok\")") { pythonFile ->
val line = 2
val sdk = PythonSdkUtil.findPythonSdk(myFixture.module)
val skeletonsDir = findSkeletonsDir(sdk!!)
val pythonFile = skeletonsDir!!.findFileByRelativePath("datetime.py")
val line = 20
val document = FileDocumentManager.getInstance().getDocument(pythonFile)
val range = TextRange.create(document!!.getLineStartOffset(line), document.getLineEndOffset(line))
assertEquals(" print(\"ok\")", document.getText(range))
val document = FileDocumentManager.getInstance().getDocument(pythonFile!!)
val range = TextRange.create(document!!.getLineStartOffset(line), document.getLineEndOffset(line))
assertEquals(" pass", document.getText(range))
assertFalse(PyLineBreakpointType().canPutAt(pythonFile, line, myFixture.project))
}
assertFalse(PyLineBreakpointType().canPutAt(pythonFile, line, myFixture.project))
}
// PY-16932
@@ -28,11 +28,9 @@ class PyNavigationTest : PyTestCase() {
// PY-35129
fun testGoToDeclarationForDirectory() {
runWithAdditionalFileInLibDir("collections/__init__.py", "") {
configureByDir(getTestName(true))
val target = PyGotoDeclarationHandler().getGotoDeclarationTarget(elementAtCaret, myFixture.editor)
checkPyNotPyi(target)
}
configureByDir(getTestName(true))
val target = PyGotoDeclarationHandler().getGotoDeclarationTarget(elementAtCaret, myFixture.editor)
checkPyNotPyi(target)
}
private fun configureByDir(dirName: String) {
@@ -68,43 +68,16 @@ public class PyOptimizeImportsTest extends PyTestCase {
}
public void testOrderByType() {
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doTest()
)
);
doTest();
}
// PY-12018
public void testAlphabeticalOrder() {
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doTest()
)
);
doTest();
}
public void testInsertBlankLines() { // PY-8355
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doTest()
)
);
doTest();
}
// PY-16351
@@ -148,16 +121,7 @@ public class PyOptimizeImportsTest extends PyTestCase {
// PY-18792
public void testDisableAlphabeticalOrder() {
getPythonCodeStyleSettings().OPTIMIZE_IMPORTS_SORT_IMPORTS = false;
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doTest()
)
);
doTest();
}
// PY-18792, PY-19292
@@ -263,20 +227,7 @@ public class PyOptimizeImportsTest extends PyTestCase {
// PY-18972
public void testReferencesInFStringLiterals() {
runWithLanguageLevel(
LanguageLevel.PYTHON36,
() ->
runWithAdditionalFileInLibDir(
"sys.py",
"",
(__) ->
runWithAdditionalFileInLibDir(
"datetime.py",
"",
(___) -> doTest()
)
)
);
runWithLanguageLevel(LanguageLevel.PYTHON36, this::doTest);
}
// PY-22355
@@ -10,9 +10,6 @@ import com.jetbrains.python.documentation.PythonDocumentationProvider;
import com.jetbrains.python.documentation.docstrings.DocStringFormat;
import com.jetbrains.python.fixtures.LightMarkedTestCase;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.sdk.PythonSdkType;
import com.jetbrains.python.sdk.PythonSdkUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
@@ -329,19 +326,7 @@ public class PyQuickDocTest extends LightMarkedTestCase {
// PY-22685
public void testBuiltinLen() {
final LanguageLevel languageLevel = PythonSdkType.getLanguageLevelForSdk(PythonSdkUtil.findPythonSdk(myFixture.getModule()));
runWithAdditionalFileInLibDir(
PyBuiltinCache.getBuiltinsFileName(languageLevel),
"def len(p_object): # real signature unknown; restored from __doc__\n" +
" \"\"\"\n" +
" len(object) -> integer\n" +
" \n" +
" Return the number of items of a sequence or collection.\n" +
" \"\"\"\n" +
" return 0",
(__) -> checkHTMLOnly()
);
checkHTMLOnly();
}
public void testArgumentList() {
@@ -369,16 +354,7 @@ public class PyQuickDocTest extends LightMarkedTestCase {
}
public void testReferenceToMethodQualifiedWithInstance() {
final LanguageLevel languageLevel = PythonSdkType.getLanguageLevelForSdk(PythonSdkUtil.findPythonSdk(myFixture.getModule()));
runWithAdditionalFileInLibDir(
PyBuiltinCache.getBuiltinsFileName(languageLevel),
"class list(object):\n" +
" def count(self, value): # real signature unknown; restored from __doc__\n" +
" \"\"\" L.count(value) -> integer -- return number of occurrences of value \"\"\"\n" +
" return 0",
(__) -> checkHTMLOnly()
);
checkHTMLOnly();
}
public void testOneDecoratorFunction() {
@@ -8,9 +8,6 @@ import com.jetbrains.python.documentation.docstrings.DocStringFormat;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.inspections.*;
import com.jetbrains.python.psi.LanguageLevel;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.sdk.PythonSdkType;
import com.jetbrains.python.sdk.PythonSdkUtil;
/**
* @author yole
@@ -228,17 +225,7 @@ public class PythonInspectionsTest extends PyTestCase {
}
public void testPyArgumentEqualDefaultInspection() { //PY-3125
final LanguageLevel languageLevel = PythonSdkType.getLanguageLevelForSdk(PythonSdkUtil.findPythonSdk(myFixture.getModule()));
runWithAdditionalFileInLibDir(
PyBuiltinCache.getBuiltinsFileName(languageLevel),
"class property(object):\n" +
" def __init__(self, fget=None, fset=None, fdel=None, doc=None):\n" +
" pass\n" +
"def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):\n" +
" pass",
(__) -> doHighlightingTest(PyArgumentEqualDefaultInspection.class)
);
doHighlightingTest(PyArgumentEqualDefaultInspection.class);
}
public void testPyArgumentEqualDefaultInspectionPy3() {
@@ -21,7 +21,6 @@ import com.intellij.openapi.projectRoots.impl.MockSdk;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.jetbrains.python.codeInsight.typing.PyTypeShed;
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil;
@@ -32,7 +31,6 @@ import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.Arrays;
/**
* @author yole
@@ -50,22 +48,30 @@ public class PythonMockSdk {
SdkType sdkType = PythonSdkType.getInstance();
MultiMap<OrderRootType, VirtualFile> roots = MultiMap.create();
OrderRootType classes = OrderRootType.CLASSES;
ContainerUtil.putIfNotNull(classes, LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(mock_path, "Lib")), roots);
File libPath = new File(mock_path, "Lib");
if (libPath.exists()) {
roots.putValue(OrderRootType.CLASSES, LocalFileSystem.getInstance().refreshAndFindFileByIoFile(libPath));
}
ContainerUtil.putIfNotNull(classes, PyUserSkeletonsUtil.getUserSkeletonsDirectory(), roots);
roots.putValue(OrderRootType.CLASSES, PyUserSkeletonsUtil.getUserSkeletonsDirectory());
final LanguageLevel level = LanguageLevel.fromPythonVersion(version);
final VirtualFile typeShedDir = PyTypeShed.INSTANCE.getDirectory();
PyTypeShed.INSTANCE
.findRootsForLanguageLevel(level)
.forEach(path -> ContainerUtil.putIfNotNull(classes, typeShedDir.findFileByRelativePath(path), roots));
assert typeShedDir != null;
PyTypeShed.INSTANCE.findRootsForLanguageLevel(level).forEach(path -> {
final VirtualFile file = typeShedDir.findFileByRelativePath(path);
if (file != null) {
roots.putValue(OrderRootType.CLASSES, file);
}
});
String mock_stubs_path = mock_path + PythonSdkUtil.SKELETON_DIR_NAME;
ContainerUtil.putIfNotNull(classes, LocalFileSystem.getInstance().refreshAndFindFileByPath(mock_stubs_path), roots);
roots.putValue(PythonSdkUtil.BUILTIN_ROOT_TYPE, LocalFileSystem.getInstance().refreshAndFindFileByPath(mock_stubs_path));
roots.putValues(classes, Arrays.asList(additionalRoots));
for (final VirtualFile root : additionalRoots) {
roots.putValue(OrderRootType.CLASSES, root);
}
MockSdk sdk = new MockSdk(MOCK_SDK_NAME + " " + version, sdkHome, "Python " + version + " Mock SDK", roots, sdkType);
@@ -40,7 +40,10 @@ import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.testFramework.*;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.TestDataPath;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.fixtures.*;
import com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl;
import com.intellij.usageView.UsageInfo;
@@ -59,7 +62,6 @@ import com.jetbrains.python.formatter.PyCodeStyleSettings;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyFileImpl;
import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher;
import com.jetbrains.python.psi.search.PySearchUtilBase;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import com.jetbrains.python.sdk.PythonSdkUtil;
@@ -70,7 +72,6 @@ import org.junit.Assert;
import javax.swing.*;
import java.io.File;
import java.util.*;
import java.util.function.Consumer;
/**
* @author yole
@@ -170,33 +171,6 @@ public abstract class PyTestCase extends UsefulTestCase {
return new LightTempDirTestFixtureImpl(true); // "tmp://" dir by default
}
protected void runWithAdditionalFileInLibDir(@NotNull String relativePath,
@NotNull String text,
@NotNull Consumer<VirtualFile> consumer) {
final Sdk sdk = PythonSdkUtil.findPythonSdk(myFixture.getModule());
runWithAdditionalFileIn(relativePath, text, PySearchUtilBase.findLibDir(sdk), consumer);
}
protected void runWithAdditionalFileInSkeletonDir(@NotNull String relativePath,
@NotNull String text,
@NotNull Consumer<VirtualFile> consumer) {
final Sdk sdk = PythonSdkUtil.findPythonSdk(myFixture.getModule());
runWithAdditionalFileIn(relativePath, text, PythonSdkUtil.findSkeletonsDir(sdk), consumer);
}
private void runWithAdditionalFileIn(@NotNull String relativePath,
@NotNull String text,
@NotNull VirtualFile dir,
@NotNull Consumer<VirtualFile> consumer) {
final VirtualFile file = VfsTestUtil.createFile(dir, relativePath, text);
try {
consumer.accept(file);
}
finally {
VfsTestUtil.deleteFile(file);
}
}
protected void runWithAdditionalClassEntryInSdkRoots(@NotNull VirtualFile directory, @NotNull Runnable runnable) {
final Sdk sdk = PythonSdkUtil.findPythonSdk(myFixture.getModule());
assertNotNull(sdk);
@@ -190,6 +190,11 @@ public class PyArgumentListInspectionTest extends PyInspectionTestCase {
doTest();
}
// PY-19716
public void testMethodsForLoggingExceptions() {
doMultiFileTest("b.py");
}
// PY-19522
public void testCsvRegisterDialect() {
doMultiFileTest("b.py");
@@ -540,6 +540,11 @@ public class PyUnresolvedReferencesInspectionTest extends PyInspectionTestCase {
doTest();
}
// PY-20071
public void testNonexistentLoggerMethod() {
doMultiFileTest();
}
// PY-21224
public void testSixWithMetaclass() {
doTest();
@@ -74,25 +74,12 @@ public class PyAddImportQuickFixTest extends PyQuickFixTestCase {
// PY-21563
public void testCombineFromImportsForReferencesInTypeComment() {
doMultiFileAutoImportTest("Import 'typing.Set'");
doMultiFileAutoImportTest("Import this name");
}
// PY-25234
public void testBinarySkeletonStdlibModule() {
runWithAdditionalFileInLibDir(
"re.py",
"",
(__) ->
runWithAdditionalFileInSkeletonDir(
"sys.py",
"# encoding: utf-8\n" +
"# module sys\n" +
"# from (built-in)\n" +
"# by generator 1.138\n" +
"path = 10",
(___) -> doMultiFileAutoImportTest("Import 'sys'")
)
);
doMultiFileAutoImportTest("Import 'sys'");
}
// PY-25234
@@ -155,20 +142,12 @@ public class PyAddImportQuickFixTest extends PyQuickFixTestCase {
// PY-20976
public void testOrderingLocalBeforeStdlib() {
runWithAdditionalFileInLibDir(
"sys.py",
"path = 10",
(__) -> doTestProposedImportsOrdering("path", "pkg.path", "sys.path", "os.path")
);
doTestProposedImportsOrdering("path", "pkg.path", "sys.path", "os.path");
}
// PY-20976
public void testOrderingUnderscoreInPath() {
runWithAdditionalFileInLibDir(
"sys.py",
"path = 10",
(__) -> doTestProposedImportsOrdering("path", "first.second.path", "sys.path", "os.path", "_private.path")
);
doTestProposedImportsOrdering("path", "first.second.path", "sys.path", "os.path", "_private.path");
}
// PY-20976
@@ -122,11 +122,7 @@ class PyInlineFunctionTest : PyTestCase() {
fun testOverridden() = doTestError("Cannot inline overridden methods")
fun testNested() = doTestError("Cannot inline functions with another function declaration")
fun testInterruptedFlow() = doTestError("Cannot inline functions that interrupt control flow")
fun testFunctionFromBinaryStub() {
runWithAdditionalFileInSkeletonDir("sys.py", "def exit():\n pass") {
doTestError("Cannot inline function from binary module")
}
}
fun testFunctionFromBinaryStub() = doTestError("Cannot inline function from binary module")
fun testUsedAsDecorator() = doTestError("Function foo is used as a decorator and cannot be inlined. Function definition will not be removed", isReferenceError = true)
fun testUsedAsReference() = doTestError("Function foo is used as a reference and cannot be inlined. Function definition will not be removed", isReferenceError = true)
fun testUsesArgumentUnpacking() = doTestError("Function foo uses argument unpacking and cannot be inlined. Function definition will not be removed", isReferenceError = true)