我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用builtins.object()。
def __long__(self): if not hasattr(self, '__int__'): return NotImplemented return self.__int__() # not type(self).__int__(self) # def __new__(cls, *args, **kwargs): # """ # dict() -> new empty dictionary # dict(mapping) -> new dictionary initialized from a mapping object's # (key, value) pairs # dict(iterable) -> new dictionary initialized as if via: # d = {} # for k, v in iterable: # d[k] = v # dict(**kwargs) -> new dictionary initialized with the name=value pairs # in the keyword argument list. For example: dict(one=1, two=2) # """ # if len(args) == 0: # return super(newdict, cls).__new__(cls) # elif type(args[0]) == newdict: # return args[0] # else: # value = args[0] # return super(newdict, cls).__new__(cls, value)
def no(mytype, argnums=(1,)): """ A shortcut for the disallow_types decorator that disallows only one type (in any position in argnums). Example use: >>> class newstr(object): ... @no('bytes') ... def __add__(self, other): ... pass >>> newstr(u'1234') + b'1234' #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: argument can't be bytes The object can also be passed directly, but passing the string helps to prevent circular import problems. """ if isinstance(argnums, Integral): argnums = (argnums,) disallowed_types = [mytype] * len(argnums) return disallow_types(argnums, disallowed_types)
def close(fgrf=None): """ Close figure(s). Parameters ---------- fgrf : :class:`matplotlib.figure.Figure` object or integer or None, \ optional (default None) If a figure object reference or figure number is provided, close the specified figure, otherwise close all figures """ if fgrf is None: plt.close("all") else: plt.close(fgrf)
def set_dtype(self, opt, dtype): """Set the `dtype` attribute. If opt['DataType'] has a value other than None, it overrides the `dtype` parameter of this method. No changes are made if the `dtype` attribute already exists and has a value other than 'None'. Parameters ---------- opt : :class:`FISTA.Options` object Algorithm options dtype : data-type Data type for working variables (overridden by 'DataType' option) """ # Take no action of self.dtype exists has is not None if not hasattr(self, 'dtype') or self.dtype is None: # DataType option overrides explicitly specified data type if opt['DataType'] is None: self.dtype = dtype else: self.dtype = np.dtype(opt['DataType'])
def __init__(self, xshape, dtype, opt=None): """ Initialise an FISTADFT object with problem size and options. Parameters ---------- xshape : tuple of ints Shape of working variable X (the primary variable) dtype : data-type Data type for working variables opt : :class:`FISTADFT.Options` object Algorithm options """ if opt is None: opt = FISTADFT.Options() Nx = np.product(xshape) super(FISTADFT, self).__init__(Nx, xshape, dtype, opt) self.Xf = None self.Yf = None
def set_dtype(self, opt, dtype): """Set the `dtype` attribute. If opt['DataType'] has a value other than None, it overrides the `dtype` parameter of this method. No changes are made if the `dtype` attribute already exists and has a value other than 'None'. Parameters ---------- opt : :class:`ADMM.Options` object Algorithm options dtype : data-type Data type for working variables (overridden by 'DataType' option) """ # Take no action of self.dtype exists has is not None if not hasattr(self, 'dtype') or self.dtype is None: # DataType option overrides explicitly specified data type if opt['DataType'] is None: self.dtype = dtype else: self.dtype = np.dtype(opt['DataType'])
def __init__(self, xshape, dtype, opt=None): """ Initialise an ADMMEqual object with problem size and options. Parameters ---------- xshape : tuple of ints Shape of working variable X (the primary variable) dtype : data-type Data type for working variables opt : :class:`ADMMEqual.Options` object Algorithm options """ if opt is None: opt = ADMMEqual.Options() Nx = np.product(xshape) super(ADMMEqual, self).__init__(Nx, xshape, xshape, dtype, opt)
def __init__(self, Nb, yshape, dtype, opt=None): r""" Initialise an ADMMConsensus object with problem size and options. Parameters ---------- yshape : tuple Shape of variable :math:`\mathbf{y}` in objective function Nb : int Number of blocks / consensus components opt : :class:`ADMMConsensus.Options` object Algorithm options """ if opt is None: opt = ADMMConsensus.Options() self.Nb = Nb self.xshape = yshape + (Nb,) self.yshape = yshape Nx = Nb * np.prod(yshape) super(ADMMConsensus, self).__init__(Nx, yshape, self.xshape, dtype, opt)
def ntpl2array(ntpl): """ Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray` object that can be saved using :func:`numpy.savez`. Parameters ---------- ntpl : collections.namedtuple object Named tuple object to be converted to ndarray Returns ------- arr : ndarray Array representation of input named tuple """ return np.asarray((np.vstack([col for col in ntpl]), ntpl._fields, ntpl.__class__.__name__))
def array2ntpl(arr): """ Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array` back to the original :func:`collections.namedtuple` representation. Parameters ---------- arr : ndarray Array representation of named tuple constructed by :func:`ntpl2array` Returns ------- ntpl : collections.namedtuple object Named tuple object with the same name and fields as the original named typle object provided to :func:`ntpl2array` """ cls = collections.namedtuple(arr[2], arr[1]) return cls(*tuple(arr[0]))
def transpose_ntpl_list(lst): """Transpose a list of named tuple objects (of the same type) into a named tuple of lists. Parameters ---------- lst : list of collections.namedtuple object List of named tuple objects of the same type Returns ------- ntpl : collections.namedtuple object Named tuple object with each entry consisting of a list of the corresponding fields of the named tuple objects in list ``lst`` """ cls = collections.namedtuple(lst[0].__class__.__name__, lst[0]._fields) if len(lst) == 0: return None else: return cls(*[[lst[k][l] for k in range(len(lst))] for l in range(len(lst[0]))])
def make_unit(self, label, *pin_ids, **criteria): """ Create a PartUnit from a set of pins in a Part object. Parts can be organized into smaller pieces called PartUnits. A PartUnit acts like a Part but contains only a subset of the pins of the Part. Args: label: The label used to identify the PartUnit. pin_ids: A list of strings containing pin names, numbers, regular expressions, slices, lists or tuples. Keyword Args: criteria: Key/value pairs that specify attribute values the pin must have in order to be selected. Returns: The PartUnit. """ collisions = self.get_pins(label) if collisions: logger.warning("Using a label ({}) for a unit of {} that matches one or more of it's pin names ({})!".format(label, self._erc_desc(), collisions)) self.unit[label] = PartUnit(self, *pin_ids, **criteria) return self.unit[label]
def export(self): """Return a string to recreate a Part object.""" keys = self._get_fields() keys.extend(('ref_prefix','num_units','fplist','do_erc','aliases','pin','footprint')) attribs = [] attribs.append('{}={}'.format('name',repr(self.name))) attribs.append('dest=TEMPLATE') attribs.append('tool=SKIDL') for k in keys: v = getattr(self, k, None) if v: attribs.append('{}={}'.format(k,repr(v))) if self.pins: pin_strs = [p.export() for p in self.pins] attribs.append('pins=[{}]'.format(','.join(pin_strs))) return 'Part({})'.format(','.join(attribs))
def __init__(self, name, *args, **attribs): # Define the member storing the nets so it's present, but it starts empty. self.nets = [] # For Bus objects, the circuit object the bus is a member of is passed # in with all the other attributes. If a circuit object isn't provided, # then the default circuit object is added to the attributes. attribs['circuit'] = attribs.get('circuit', default_circuit) # Attach additional attributes to the bus. (The Circuit object also gets # set here.) for k, v in attribs.items(): setattr(self, k, v) # The bus name is set after the circuit is assigned so the name can be # checked against the other bus names already in that circuit. self.name = name # Add the bus to the circuit. self.circuit = None # Bus won't get added if it's already seen as part of circuit. attribs['circuit'] += self # Add bus to circuit. This also sets self.circuit again. # Build the bus from net widths, existing nets, nets of pins, other buses. self.extend(args)
def add_nets(self, *nets): """Add some Net objects to the circuit. Assign a net name if necessary.""" for net in nets: # Add the net to this circuit if the net is movable and # it's not already in this circuit. if net.circuit != self: if net._is_movable(): # Remove the net from the circuit it's already in. if isinstance(net.circuit, Circuit): net.circuit -= net # Add the net to this circuit. net.circuit = self # Record the Circuit object the net belongs to. net.name = net.name net.hierarchy = self.hierarchy # Tag the net with its hierarchy position. self.nets.append(net) else: logger.error("Can't add unmovable net {} to this circuit.".format(net.name)) raise Exception
def backup_parts(self, file=None): """ Saves parts in circuit as a SKiDL library in a file. Args: file: Either a file object that can be written to, or a string containing a file name, or None. If None, a standard library file will be used. Returns: Nothing. """ lib = SchLib(tool=SKIDL) # Create empty library. for p in self.parts: lib += p if not file: file = BACKUP_LIB_FILE_NAME lib.export(libname=BACKUP_LIB_NAME, file=file)
def show(lib, part_name, tool=None): """ Print the I/O pins for a given part in a library. Args: lib: Either a SchLib object or the name of a library. part_name: The name of the part in the library. tool: The ECAD tool format for the library. Returns: A Part object. """ if tool is None: tool = DEFAULT_TOOL try: return Part(lib, re.escape(part_name), tool=tool, dest=TEMPLATE) except Exception: return None
def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args # 'try' clause is to attempt to handle the possibility that inspect # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. if inspect.isgetsetdescriptor(object): return self.docdata(*args) if inspect.ismemberdescriptor(object): return self.docdata(*args) try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass if isinstance(object, property): return self.docproperty(*args) return self.docother(*args)
def render_doc(thing, title='Python Library Documentation: %s', forceload=0, renderer=None): """Render text documentation, given an object or a path to an object.""" if renderer is None: renderer = text object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + renderer.document(object, name)
def get_fernet(): """ Deferred load of Fernet key. This function could fail either because Cryptography is not installed or because the Fernet key is invalid. :return: Fernet object :raises: AirflowException if there's a problem trying to load Fernet """ try: from cryptography.fernet import Fernet except: raise AirflowException('Failed to import Fernet, it may not be installed') try: return Fernet(configuration.get('core', 'FERNET_KEY').encode('utf-8')) except ValueError as ve: raise AirflowException("Could not create Fernet object: {}".format(ve))
def setdefault(cls, key, default, deserialize_json=False): """ Like a Python builtin dict object, setdefault returns the current value for a key, and if it isn't there, stores the default value and returns it. :param key: Dict key for this Variable :type key: String :param default: Default value to set and return if the variable isn't already in the DB :type default: Mixed :param deserialize_json: Store this as a JSON encoded value in the DB and un-encode it when retrieving a value :return: Mixed """ default_sentinel = object() obj = Variable.get(key, default_var=default_sentinel, deserialize_json=deserialize_json) if obj is default_sentinel: if default is not None: Variable.set(key, default, serialize_json=deserialize_json) return default else: raise ValueError('Default Value must be set') else: return obj
def test_oldstyle_classes(self): """ Stage 2 should convert old-style to new-style classes. This makes the new-style class explicit and reduces the gap between the behaviour (e.g. method resolution order) on Py2 and Py3. It also allows us to provide ``newobject`` (see test_oldstyle_classes_iterator). """ before = """ class Blah: pass """ after = """ from builtins import object class Blah(object): pass """ self.convert_check(before, after, ignore_imports=False)
def __init__(self, state, event, machine, model, args, kwargs): """ Args: state (State): The State from which the Event was triggered. event (Event): The triggering Event. machine (Machine): The current Machine instance. model (object): The model/object the machine is bound to. args (list): Optional positional arguments from trigger method to store internally for possible later use. kwargs (dict): Optional keyword arguments from trigger method to store internally for possible later use. """ self.state = state self.event = event self.machine = machine self.model = model self.args = args self.kwargs = kwargs
def create_from_json(cls, json_data): """Deserialize block json data into a Block object Args: json_data (dict): The json data for this block Returns: Block object """ block = Block() block_info = json_data["block_info"] block.block_id = block_info["block_id"] block.num_bins = block_info["num_bins"] if "num_bins" in block_info else None block.property_type = block_info["property_type"] if "property_type" in block_info else None block.meta = json_data["meta"] if "meta" in json_data else None block.component_results = _create_component_results(json_data, "block_info") return block
def create_from_json(cls, json_data): """Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip object """ zipcode = ZipCode() zipcode.zipcode = json_data["zipcode_info"]["zipcode"] zipcode.meta = json_data["meta"] if "meta" in json_data else None zipcode.component_results = _create_component_results(json_data, "zipcode_info") return zipcode
def create_from_json(cls, json_data): """Deserialize msa json data into a Msa object Args: json_data (dict): The json data for this msa Returns: Msa object """ msa = Msa() msa.msa = json_data["msa_info"]["msa"] msa.meta = json_data["meta"] if "meta" in json_data else None msa.component_results = _create_component_results(json_data, "msa_info") return msa
def post(self, url, post_data, query_params=None): """Makes a POST request to the specified url endpoint. Args: url (string): The url to the API without query params. Example: "https://api.housecanary.com/v2/property/value" post_data: Json post data to send in the body of the request. query_params (dict): Optional. Dictionary of query params to add to the request. Returns: The result of calling this instance's OutputGenerator process_response method on the requests.Response object. If no OutputGenerator is specified for this instance, returns the requests.Response. """ if query_params is None: query_params = {} return self.execute_request(url, "POST", query_params, post_data)
def test_allmethods(self): # issue 17476: allmethods was no longer returning unbound methods. # This test is a bit fragile in the face of changes to object and type, # but I can't think of a better way to do it without duplicating the # logic of the function under test. class TestClass(object): def method_returning_true(self): return True # What we expect to get back: everything on object... expected = dict(vars(object)) # ...plus our unbound method... expected['method_returning_true'] = TestClass.method_returning_true # ...but not the non-methods on object. del expected['__doc__'] del expected['__class__'] # inspect resolves descriptors on type into methods, but vars doesn't, # so we need to update __subclasshook__. expected['__subclasshook__'] = TestClass.__subclasshook__ methods = pydoc.allmethods(TestClass) self.assertDictEqual(methods, expected)
def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" parts = [part for part in path.split('.') if part] module, n = None, 0 while n < len(parts): nextmodule = safeimport('.'.join(parts[:n+1]), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: object = module else: object = builtins for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object # --------------------------------------- interactive interpreter interface
def __init__(self, sentences=None, mtype='sg', embed_dim=100, hs=1, neg=0, thr=0, window=5, min_count=5, alpha=0.025, min_alpha=0.0001, seed=1): """ Initialize Word2Vec model Inputs: - sentences: (default None) List or generator object supplying lists of (preprocessed) words used to train the model (otherwise train manually with model.train(sentences)) - mtype: (default 'sg') type of model: either 'sg' (skipgram) or 'cbow' (bag of words) - embed_dim: (default 100) dimensionality of embedding - hs: (default 1) if != 0, hierarchical softmax will be used for training the model - neg: (default 0) if > 0, negative sampling will be used for training the model; neg specifies the # of noise words - thr: (default 0) threshold for computing probabilities for sub-sampling words in training - window: (default 5) max distance of context words from target word in training - min_count: (default 5) how often a word has to occur at least to be taken into the vocab - alpha: (default 0.025) initial learning rate - min_alpha: (default 0.0001) if < alpha, the learning rate will be decreased to min_alpha - seed: (default 1) random seed (for initializing the embeddings) """ assert mtype in ('sg', 'cbow'), "unknown model, use 'sg' or 'cbow'" self.vocab = {} # mapping from a word (string) to a Vocab object self.index2word = [] # map from a word's matrix index (int) to the word (string) self.mtype = mtype self.embed_dim = embed_dim self.hs = hs self.neg = neg self.thr = thr self.window = window self.min_count = min_count self.alpha = alpha self.min_alpha = min_alpha self.seed = seed # possibly train model if sentences: self.build_vocab(sentences) self.train(sentences)
def process_class_name(self, name, bases, module): """Format the class's name and bases.""" title = "## class " + self.bold(name) if bases: # get the names of each of the bases base_titles = [pydoc.classname(base, module) for base in bases] # if its not just object if len(base_titles) > 1: # append the list to the title title += "(%s)" % ", ".join(base_titles) return title
def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): object = object.__func__ if name == realname: title = self.bold(realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = inspect.getfullargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann, formatvalue=self.formatvalue, formatannotation=inspect.formatannotationrelativeto(object)) if realname == '<lambda>': title = self.bold(name) + ' lambda ' # XXX lambda's won't usually have func_annotations['return'] # since the syntax doesn't support but it is possible. # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = "#### " + "def " + title + argspec + ':' + '\n' + note if skipdocs: return decl + '\n' else: doc = pydoc.getdoc(object) or '' return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n')
def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" line = "#### " + object.__name__ + "\n" line += super().docother(object, name, mod, parent, maxlen, doc) return line + "\n"
def _is_bytes_like(obj): """ Check whether obj behaves like a bytes object. """ try: obj + asbytes('') except (TypeError, ValueError): return False return True
def span_in_context(span): """ Create a context manager that stores the given span in the thread-local request context. This function should only be used in single-threaded applications like Flask / uWSGI. ## Usage example in WSGI middleware: .. code-block:: python from opentracing_instrumentation.http_server import WSGIRequestWrapper from opentracing_instrumentation.http_server import before_request from opentracing_instrumentation import request_context def create_wsgi_tracing_middleware(other_wsgi): def wsgi_tracing_middleware(environ, start_response): request = WSGIRequestWrapper.from_wsgi_environ(environ) span = before_request(request=request, tracer=tracer) # Wrapper around the real start_response object to log # additional information to opentracing Span def start_response_wrapper(status, response_headers, exc_info=None): if exc_info is not None: span.log(event='exception', payload=exc_info) span.finish() return start_response(status, response_headers) with request_context.span_in_context(span): return other_wsgi(environ, start_response_wrapper) return wsgi_tracing_middleware :param span: OpenTracing Span :return: Return context manager that wraps the request context. """ context = RequestContext(span) return RequestContextManager(context)
def test_decorator_with_name(self): class SomeClient(object): @traced_function(name='func2_modified') @gen.coroutine def func2(self, param1): assert param1 == 123 raise tornado.gen.Return('oh yeah') s = SomeClient() parent = opentracing.tracer.start_span('hello') @gen.coroutine def run(): # verify start_span is called with overridden function name child = mock.MagicMock() with patch_object(opentracing.tracer, 'start_span', return_value=child) as start_child: child.set_tag = mock.MagicMock() r = yield s.func2(123) assert r == 'oh yeah' start_child.assert_called_once_with( operation_name='func2_modified', # overridden name child_of=parent.context, tags=None) assert child.set_tag.call_count == 0 raise tornado.gen.Return(1) yield run_coroutine_with_span(span=parent, coro=run)
def test_decorator_with_start_hook(self): class SomeClient(object): @traced_function(on_start=extract_call_site_tag) def func3(self, param1, param2=None, call_site_tag=None): assert param1 == call_site_tag assert param2 is None return 'oh yeah' # not a co-routine s = SomeClient() parent = opentracing.tracer.start_span('hello') @gen.coroutine def run(): # verify call_size_tag argument is extracted and added as tag child = mock.MagicMock() with patch_object(opentracing.tracer, 'start_span') \ as start_child: start_child.return_value = child child.set_tag = mock.MagicMock() r = s.func3('somewhere', call_site_tag='somewhere') assert r == 'oh yeah' start_child.assert_called_once_with( operation_name='func3', child_of=parent.context, tags=None) child.set_tag.assert_called_once_with( 'call_site_tag', 'somewhere') raise tornado.gen.Return(1) yield run_coroutine_with_span(span=parent, coro=run)
def test_inherit_1(self): md = MetaData() class Hi(object): __metadata__ = md class User(Table, Hi): id = HashKeyField() mapper = User.__mapper__ assert mapper.metadata == md assert mapper in md
def test_inherit(self): class Hi(object): __tablename__ = 'iamname' name = Field() class User(Table, Hi): id = HashKeyField() class BoomUser(User): __tablename__ = "boom" boom = Field() assert User.__mapper__.tablename == 'iamname' assert BoomUser.__mapper__.tablename == 'boom'
def test_inherit_2(self): tp = {'read': 1, 'write': 6} class Hi(object): __throughput__ = tp class User(Table, Hi): id = HashKeyField() mapper = User.__mapper__ assert mapper.throughput == tp
def test_inherit_1(self): class Hi(object): id = HashKeyField() class User(Table, Hi): name = RangeKeyField(data_type=NUMBER) self._check_rangekey(User)
def test_inherit_1(self): class Hi(object): id = HashKeyField() class User(Table, Hi): name = Field(data_type=NUMBER) mapper = User.__mapper__ assert User.id is mapper.attributes['id'] assert User.name is mapper.attributes['name']
def test_dynamizer(): md = MetaData() assert md.dynamizer is None with pytest.raises(ArgumentError): md.configure(dynamizer=object) md.configure(dynamizer=DummyDynamizer) assert md.dynamizer is DummyDynamizer
def test_notify(self): """ The notify() API allows getting all events passed to the Discovery instance. """ disco = create_disco() messages = [object(), NodeActive(create_node("hello"))] result = [] disco.notify(result.append) for m in messages: disco.onMessage(None, m) self.assertEqual(messages, result)