class UnionTypeExampleVisitor(ABCMeta('ABC', (object, ), {})): @abstractmethod def _string_example(self, string_example): # type: (StringExample) -> Any pass @abstractmethod def _set(self, set): # type: (List[str]) -> Any pass @abstractmethod def _this_field_is_an_integer(self, this_field_is_an_integer): # type: (int) -> Any pass @abstractmethod def _also_an_integer(self, also_an_integer): # type: (int) -> Any pass @abstractmethod def _if(self, if_): # type: (int) -> Any pass @abstractmethod def _new(self, new): # type: (int) -> Any pass @abstractmethod def _interface(self, interface): # type: (int) -> Any pass
def mk_awaitable(): from abc import abstractmethod, ABCMeta @abstractmethod def __await__(self): yield @classmethod def __subclasshook__(cls, C): if cls is Awaitable: for B in C.__mro__: if '__await__' in B.__dict__: if B.__dict__['__await__']: return True break return NotImplemented # calling metaclass directly as syntax differs in Py2/Py3 Awaitable = ABCMeta( 'Awaitable', (), { '__slots__': (), '__await__': __await__, '__subclasshook__': __subclasshook__, }) return Awaitable
class ServerSetProvider(ABCMeta('ABCMeta', (object, ), {})): """Base class for providing a set of servers, as well as optionally notifying the pool of servers joining and leaving the set.""" @abstractmethod def Initialize(self, on_join, on_leave): """Initialize the provider. This method is called before any calls to GetServers(). Args: on_join - A function to be called when a server joins the set. on_leave - A function to be called when a server leaves the set. """ raise NotImplementedError() @abstractmethod def Close(self): """Close the provider and any resources associated. """ raise NotImplementedError() @abstractmethod def GetServers(self): """Get all the current servers in the set. Returns: An iterable of servers. """ raise NotImplementedError() @property def endpoint_name(self): return None
def _bake(name): class Doc(str): def __init__(self, registry, *argv, **kwarg): self.registry = registry super(Doc, self).__init__(*argv, **kwarg) def __repr__(self): return repr(self.registry['doc']) def __str__(self): return str(self.registry['doc']) def expandtabs(self, ts=4): return self.registry['doc'].expandtabs(ts) class Registry(object): def __init__(self): self.target = {} def __getitem__(self, key): if not self.target: module = __import__(_modules[name], globals(), locals(), [name], 0) self.target['class'] = getattr(module, name) self.target['doc'] = self.target['class'].__doc__ try: self.target['doc'] += _DISCLAIMER except TypeError: # ignore cases, when __doc__ is not a string, e.g. None pass return self.target[key] @classmethod def __hook__(cls, C): if hasattr(C, 'registry'): try: return issubclass(C.registry['class'], cls.registry['class']) except Exception: pass return issubclass(C, cls.registry['class']) def __new__(cls, *argv, **kwarg): cls.register(cls.registry['class']) return cls.registry['class'](*argv, **kwarg) registry = Registry() doc = Doc(registry) proxy = ABCMeta('proxy', (object, ), {'__new__': __new__, '__doc__': doc, '__subclasshook__': __hook__, 'registry': registry}) return proxy
class Agent(ABCMeta('ABC', (object, ), {})): @abstractmethod def is_done(self, action_result): """ Method should return a Boolean denoting whether your agent is done with the task or not. The 'action_result' argument should be used to inform your decision. Note that if the value is 'ActionResult.COLLIDED' or 'BenchBot.FINISHED', BenchBot will no longer report any available actions via 'BenchBot.actions' so your method needs to return True in these cases """ return False @abstractmethod def pick_action(self, observations, action_list): """ Method should return a selected action from the list provided by 'BenchBot.actions', & a dictionary of argument values required for the action. The following example would move the robot forward 10cm: return 'move_distance', {'distance': 0.1} This method is also where your agent should also use the observations to update its semantic understanding of the world. The list of available actions returned from 'BenchBot.actions' will change based on the mode selected, & the last action_result returned by 'BenchBot.step'. Your code below should select a valid action from the list, otherwise 'BenchBot.step' will throw an exception trying to execute an invalid action. The current list of possible actions (& required arguments) is available here: https://github.com/qcr/benchbot_api#standard-communication-channels """ return None @abstractmethod def save_result(self, filename, empty_results, results_format_fns): """ Method should write your results for the task to the file specified by 'filename'. The method returns no value, so if there is any failure in writing results an exception should be raised. Results must be specified in the format defined by the current task (see 'BenchBot.config' for details). The 'empty_results' argument is pre-populated with necessary fields common to all results ('environment_details' & 'task_details'), as well as the return of the results format's 'create' function. The 'results_format_fns' contains all of the functions defined for that format, and can be useful for specialist actions (e.g. creating objects in scene understanding object maps). """ return
class Listening(ABCMeta('ABC', (), {})): # https://github.com/GoogleCloudPlatform/python-docs-samples/blob/ # speech-continuous/speech/cloud-client/transcribe_streaming_indefinite.py DEFAULT_RATE = 16000 DEFAULT_CHUNK = 1600 DEFAULT_LANG = 'en-US' def __init__(self, rate = DEFAULT_RATE, chunk = DEFAULT_CHUNK, language_code = DEFAULT_LANG): # add google auth info for speech recognition (assuming file location) auth_location = real_dirname() + '/google-speech-recog-auth.json' os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = auth_location # add instance variables self._rate = rate self._chunk = int(self._rate / 10) self.language_code = language_code @abstractmethod def process_speech(transcript): pass def config_and_start(self, wake_word): client = speech.SpeechClient() config = types.RecognitionConfig( encoding = enums.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz = self._rate, language_code = self.language_code) streaming_config = types.StreamingRecognitionConfig( config = config, interim_results = True) with MicrophoneStream(self._rate, self._chunk) as stream: audio_generator = stream.generator() requests = (types.StreamingRecognizeRequest(audio_content = audio) for audio in audio_generator) responses = client.streaming_recognize(streaming_config, requests) self._transcription_loop(responses, wake_word) def _transcription_loop(self, responses, wake_word): num_chars_printed = 0 if responses: for response in responses: if not response.results: continue result = response.results[0] if not result.alternatives: continue transcript = result.alternatives[0].transcript # Only process responses if they have the wake word if lazy_regex_search(wake_word, transcript): if result.is_final: self.process_speech(transcript) if lazy_regex_search('QUIT', transcript): # ask to quit break else: self.config_and_start(self.wake_word)
def register(cls, symbol, **kwargs): """ Register/update a token class in the symbol table. :param symbol: The identifier symbol for a new class or an existent token class. :param kwargs: Optional attributes/methods for the token class. :return: A token class. """ try: try: if ' ' in symbol: raise ValueError("%r: a symbol can't contain whitespaces" % symbol) except TypeError: assert isinstance(symbol, type) and issubclass(symbol, Token), \ "A %r subclass requested, not %r." % (Token, symbol) symbol, token_class = symbol.symbol, symbol assert symbol in cls.symbol_table and cls.symbol_table[symbol] is token_class, \ "Token class %r is not registered." % token_class else: token_class = cls.symbol_table[symbol] except KeyError: # Register a new symbol and create a new custom class. The new class # name is registered at parser class's module level. if symbol not in cls.SYMBOLS: raise NameError('%r is not a symbol of the parser %r.' % (symbol, cls)) kwargs['symbol'] = symbol label = kwargs.get('label', 'symbol') if isinstance(label, tuple): label = kwargs['label'] = MultiLabel(*label) token_class_name = "_{}{}".format( symbol_to_classname(symbol), str(label).title().replace(' ', '') ) token_class_bases = kwargs.get('bases', (cls.token_base_class,)) kwargs.update({ '__module__': cls.__module__, '__qualname__': token_class_name, '__return__': None }) token_class = ABCMeta(token_class_name, token_class_bases, kwargs) cls.symbol_table[symbol] = token_class MutableSequence.register(token_class) setattr(sys.modules[cls.__module__], token_class_name, token_class) else: for key, value in kwargs.items(): if key == 'lbp' and value > token_class.lbp: token_class.lbp = value elif key == 'rbp' and value > token_class.rbp: token_class.rbp = value elif callable(value): setattr(token_class, key, value) return token_class
class UnionWithImportsVisitor(ABCMeta('ABC', (object, ), {})): @abstractmethod def _string(self, string): # type: (str) -> Any pass @abstractmethod def _imported(self, imported): # type: (AnyMapExample) -> Any pass
class Subcommand(ABCMeta('ABC', (object, ), {'__slots__': ()})): # compatible metaclass with Python 2 *and* 3 """ Abstract base class for cli subcommands """ @abstractproperty def help(self): """ Help text to display at the cli for the subcommand :rtype: str """ pass @abstractproperty def name(self): """ Name of the subcommand, used as the argument to identify the subcommand on the command line :rtype: str """ pass @property def parents(self): """ List of parent :class:`argparser.ArgumentParser` instances whose options should be included for the subcommand. :rtype: list(argparse.ArgumentParser) or \ tuple(argparse.ArgumentParser) or \ set(argparse.ArgumentParser) """ return () def add_parser_args(self, parser): """ Method invoked with the :class:`argparser.ArgumentParser` added to the base parser for this subcommand. In this method call, the subcommand can add any extra subcommand-specific arguments to the parser before the cli processes them. :param argparse.ArgumentParser parser: the subcommand parser """ pass @abstractmethod def execute(self, args): """ Execution entry point for the subcommand. This method is called when the `name` of this subcommand is entered in the cli args :param argparse.Namespace args: arguments supplied to the subcommand """ pass
def test_cachedproperty_maintains_func_abstraction(): ABC = ABCMeta('ABC', (object, ), {}) class AbstractExpensiveCalculator(ABC): @cachedproperty @abstractmethod def calculate(self): pass with pytest.raises(TypeError): AbstractExpensiveCalculator()
def abstractclass(cls): """Abstract class decorator with compatibility for python 2 and 3.""" orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return ABCMeta(cls.__name__, cls.__bases__, orig_vars)
class six(object): """ A light-weight version of six (which works on IronPython) """ PY3 = sys.version_info[0] >= 3 try: from abc import ABC except ImportError: from abc import ABCMeta # type: ignore ABC = ABCMeta('ABC', (object,), {'__module__':__name__, '__slots__':()}) # type: ignore # Be sure to use named-tuple access, so that usage is not affected try: getfullargspec = staticmethod(inspect.getfullargspec) except AttributeError: getfullargspec = staticmethod(inspect.getargspec) # extra fields will not be available if PY3: integer_types = (int,) string_types = (str,) MAXSIZE = sys.maxsize ascii = ascii # @UndefinedVariable bytes = bytes # @ReservedAssignment unicode_type = str @staticmethod def b(s): return s.encode("latin-1", "replace") @staticmethod def u(s): return s @staticmethod def get_method_function(m): return m.__func__ else: integer_types = (int, long) string_types = (str, unicode) MAXSIZE = getattr(sys, "maxsize", sys.maxint) ascii = repr # @ReservedAssignment bytes = str # @ReservedAssignment unicode_type = unicode @staticmethod def b(st): return st @staticmethod def u(s): return s.decode("unicode-escape") @staticmethod def get_method_function(m): return m.im_func str = unicode_type
class ParsedVideo( ABCMeta(native_str('ParsedVideoABCMeta'), (ParsedEntry, ), {})): _old_quality = None _assumed_quality = None @abstractproperty def year(self): raise NotImplementedError @abstractproperty def subtitle_languages(self): raise NotImplementedError @abstractproperty def languages(self): raise NotImplementedError @abstractproperty def quality2(self): raise NotImplementedError @abstractproperty def is_3d(self): raise NotImplementedError @property def type(self): return 'video' @property def quality(self): if not self._old_quality: self._old_quality = self.quality2.to_old_quality( self._assumed_quality) return self._old_quality def assume_quality(self, quality): self._assumed_quality = quality self._old_quality = None def assume_quality2(self, quality2): self._assumed_quality = quality2.to_old_quality() def __str__(self): return "<%s(name=%s,year=%s,quality=%s)>" % ( self.__class__.__name__, self.name, self.year, self.quality) def __cmp__(self, other): """Compares quality of parsed, if quality is equal, compares proper_count.""" return cmp((self.quality), (other.quality)) def __eq__(self, other): return self is other
class Parser(ABCMeta(str('ParserABCMeta'), (object, ), {})): @abstractmethod def parse(self, data, type_=None, name=None, **kwargs): """ :param data: string to parse :param type_: a PARSER_* type :param attended_name: an attended name, or None is unknown :raises ParseWarning :return: an instance of :class:`ParsedEntry` """ raise NotImplementedError
def test_abstract_subclasses(self): AbstractSubclass = ABCMeta('AbstractSubclass', (greenlet, ), {'run': abstractmethod(lambda self: None)}) class BadSubclass(AbstractSubclass): pass class GoodSubclass(AbstractSubclass): def run(self): pass GoodSubclass() # should not raise self.assertRaises(TypeError, BadSubclass)
class ABCSpec(ABCMeta('APIMetaBase', (), {})): _endpoint = None _query = None _params = None Query = Query def __init__(self, *args, **kwargs): self._params = ParamList() self._query = Query() self.initialized(*args, **kwargs) @abstractmethod def __str__(self): """ Classes such as a HTTP requester that are trying to use this API spec class can invoke `__str__` on its instance to get a formatted URL. """ @abstractmethod def initialized(self): """ """ @property def extended_params(self): """ When Spec is holding extra params for some reason, this property can be used for extending parameters of `query` object. For example, URL = '{s.endpoint}/{s.query}'.format(s=self) this could be extended by rewriting like below. URL = '{s.endpoint}/{s.query.resource}?{s.extended_params}'.format(s=self) """ if self._query and self._params: return self._query.params + self._params raise AttributeError( 'Attribute both `query` and `params` should not be missing in order to extend.' ) def endpoint(self, *args, **kwargs): self._endpoint = EndPoint(*args, **kwargs) return self def query(self, resource): return self.Query(resource=resource, spec=self) def add_param(self, key, val): self._params.add_param(key, val) return self
def create_restricted_parser(cls, name: str, symbols: Sequence[str]) \ -> Type['XPath1Parser']: """Get a parser subclass with a restricted set of symbols.s""" _symbols = frozenset(symbols) symbol_table = { k: v for k, v in cls.symbol_table.items() if k in _symbols } return cast( Type['XPath1Parser'], ABCMeta(f"{name}{cls.__name__}", (cls, ), { 'symbol_table': symbol_table, 'SYMBOLS': _symbols }))
def schema_constructor(self, atomic_type_name: str, bp: int = 90) \ -> Type[XPathFunction]: """Registers a token class for a schema atomic type constructor function.""" if atomic_type_name in (XSD_ANY_ATOMIC_TYPE, XSD_NOTATION): raise xpath_error('XPST0080') def nud_(self_: XPathFunction) -> XPathFunction: self_.parser.advance('(') self_[0:] = self_.parser.expression(5), self_.parser.advance(')') try: self_.value = self_.evaluate() # Static context evaluation except MissingContextError: self_.value = None return self_ def evaluate_(self_: XPathFunction, context: Optional[XPathContext] = None) \ -> Union[List[None], AtomicValueType]: arg = self_.get_argument(context) if arg is None or self_.parser.schema is None: return [] value = self_.string_value(arg) try: return self_.parser.schema.cast_as(value, atomic_type_name) except (TypeError, ValueError) as err: raise self_.error('FORG0001', err) symbol = get_prefixed_name(atomic_type_name, self.namespaces) token_class_name = "_%sConstructorFunction" % symbol.replace(':', '_') kwargs = { 'symbol': symbol, 'nargs': 1, 'label': 'constructor function', 'pattern': r'\b%s(?=\s*\(|\s*\(\:.*\:\)\()' % symbol, 'lbp': bp, 'rbp': bp, 'nud': nud_, 'evaluate': evaluate_, '__module__': self.__module__, '__qualname__': token_class_name, '__return__': None } token_class = cast( Type[XPathFunction], ABCMeta(token_class_name, (XPathFunction, ), kwargs)) MutableSequence.register(token_class) self.symbol_table[symbol] = token_class return token_class
def _(): MyType = ABCMeta( # pylint: disable=invalid-name native_string('MyType'), (object, ), {}, ) MyType.register(int) class MyRecord(Record): value = MyType assert_eq( MyRecord(value=42).value, 42, )
def test_cachedmethod_maintains_func_abstraction(): ABC = ABCMeta('ABC', (object, ), {}) class Car(ABC): def __init__(self, cache=None): self.h_cache = LRI() if cache is None else cache self.hand_count = 0 @cachedmethod('h_cache') @abstractmethod def hand(self, *a, **kw): self.hand_count += 1 with pytest.raises(TypeError): Car()
class ParsedMovie(ABCMeta(str('ParsedMovieABCMeta'), (ParsedVideo, ), {})): @property def parsed_name(self): return self.title @property def type(self): return 'movie' @property def title(self): raise NotImplementedError @property def is_movie(self): return True
def schema_constructor(self, atomic_type, bp=90): """Registers a token class for a schema atomic type constructor function.""" if atomic_type in {XSD_ANY_ATOMIC_TYPE, XSD_NOTATION}: raise xpath_error('XPST0080') def nud_(self_): self_.parser.advance('(') self_[0:] = self_.parser.expression(5), self_.parser.advance(')') try: self_.value = self_.evaluate() # Static context evaluation except MissingContextError: self_.value = None return self_ def evaluate_(self_, context=None): arg = self_.get_argument(context) if arg is None: return [] value = self_.string_value(arg) try: return self_.parser.schema.cast_as(value, atomic_type) except (TypeError, ValueError) as err: raise self_.error('FORG0001', err) symbol = get_prefixed_name(atomic_type, self.namespaces) token_class_name = str("_%s_constructor_token" % symbol.replace(':', '_')) kwargs = { 'symbol': symbol, 'label': 'constructor function', 'pattern': r'\b%s(?=\s*\(|\s*\(\:.*\:\)\()' % symbol, 'lbp': bp, 'rbp': bp, 'nud': nud_, 'evaluate': evaluate_, '__module__': self.__module__, '__qualname__': token_class_name, '__return__': None } token_class = ABCMeta(token_class_name, (self.token_base_class, ), kwargs) MutableSequence.register(token_class) self.symbol_table[symbol] = token_class return token_class
class six(object): """ A light-weight version of six (which works on IronPython) """ PY3 = sys.version_info[0] >= 3 ABC = ABCMeta('ABC', (object, ), {'__module__': __name__}) if PY3: integer_types = (int, ) string_types = (str, ) MAXSIZE = sys.maxsize ascii = ascii # @UndefinedVariable bytes = bytes # @ReservedAssignment unicode_type = str @staticmethod def b(s): return s.encode("latin-1", "replace") @staticmethod def u(s): return s @staticmethod def get_method_function(m): return m.__func__ else: integer_types = (int, long) string_types = (str, unicode) MAXSIZE = getattr(sys, "maxsize", sys.maxint) ascii = repr # @ReservedAssignment bytes = str # @ReservedAssignment unicode_type = unicode @staticmethod def b(st): return st @staticmethod def u(s): return s.decode("unicode-escape") @staticmethod def get_method_function(m): return m.im_func
def _new_in_ver(name, ver, bases_if_missing=(ABCMeta,), register_if_missing=()): if ver: return getattr(abc, name) # TODO: It's a shame to have to repeat the bases when # the ABC is missing. Can we DRY that? missing = ABCMeta(name, bases_if_missing, { '__doc__': "The ABC %s is not defined in this version of Python." % ( name ), }) for c in register_if_missing: missing.register(c) return missing
class ParsedVideoQuality( ABCMeta(native_str('ParsedVideoQualityABCMeta'), (object, ), {})): @abstractproperty def screen_size(self): raise NotImplementedError @abstractproperty def source(self): raise NotImplementedError @abstractproperty def format(self): raise NotImplementedError @abstractproperty def video_codec(self): raise NotImplementedError @abstractproperty def video_profile(self): raise NotImplementedError @abstractproperty def audio_codec(self): raise NotImplementedError @abstractproperty def audio_profile(self): raise NotImplementedError @abstractproperty def audio_channels(self): raise NotImplementedError @abstractmethod def to_old_quality(self, assumed_quality=None): raise NotImplementedError def __str__(self): return "<%s(screen_size=%s,source=%s,video_codec=%s,audio_channels=%s)>" % ( self.__class__.__name__, self.screen_size, self.source, self.video_codec, self.audio_channels)
class MessageSink(ABCMeta('ABCMeta', (object, ), {})): """A base class for all message sinks. MessageSinks form a cooperative linked list, which each sink calling the next sink in the chain once it's processing is complete. """ __slots__ = '_next', def __init__(self): super(MessageSink, self).__init__() self._next = None @property def next_sink(self): """The next sink in the chain.""" return self._next @next_sink.setter def next_sink(self, value): self._next = value
def decorator(clazz): assert isclass(clazz), 'Invalid class %s' % clazz calls = [] for name, function in clazz.__dict__.items(): if isfunction(function): try: calls.append(function._ally_call) except AttributeError: raise DevelError('No call for method at:\n%s' % locationStack(function)) del function._ally_call services = [typeFor(base) for base in clazz.__bases__] services = [ typ.service for typ in services if isinstance(typ, TypeService) ] names = {call.name for call in calls} for srv in services: assert isinstance(srv, Service) for name, call in srv.calls.items(): assert isinstance(call, Call) if name not in names: calls.append(processGenericCall(call, generic)) names.add(name) service = Service(calls) if type(clazz) != ABCMeta: attributes = dict(clazz.__dict__) attributes.pop( '__dict__', None ) # Removing __dict__ since is a reference to the old class dictionary. attributes.pop('__weakref__', None) clazz = ABCMeta(clazz.__name__, clazz.__bases__, attributes) abstract = set(clazz.__abstractmethods__) abstract.update(service.calls) clazz.__abstractmethods__ = frozenset(abstract) clazz._ally_type = TypeService(clazz, service) # This specified the detected type for the model class by using 'typeFor' return clazz
class Item(ABCMeta('ABC', (object, ), {'__slots__': ()})): def __init__(self, x, y): self.x = x self.y = y self.active = True self.id = id(self) self.name = self.__class__.__name__ self.logic_attribute_name_list = [ 'logic_attribute_name_list', 'name', 'id', 'x', 'y', 'alive' ] def __getstate__(self): state = self.__dict__.copy() newstate = {k: state[k] for k in self.logic_attribute_name_list} return newstate def __setstate__(self, state): self.__dict__.update(state) @abstractmethod def use(self, benefitor): pass
def processAsService(clazz, service): ''' Processes the provided class as a service. @param clazz: class The class to be processed. @param service: TypeService The service to process with. @return: class The processed class. ''' assert isclass(clazz), 'Invalid class %s' % clazz assert isinstance(service, TypeService), 'Invalid service %s' % service if type(clazz) != ABCMeta: attributes = dict(clazz.__dict__) attributes.pop( '__dict__', None ) # Removing __dict__ since is a reference to the old class dictionary. attributes.pop('__weakref__', None) clazz = service.clazz = ABCMeta(clazz.__name__, clazz.__bases__, attributes) abstract = set(clazz.__abstractmethods__) abstract.update(service.calls) clazz.__abstractmethods__ = frozenset(abstract) for name, callType in service.calls.items(): callAPI = CallAPI(callType) callAPI.__isabstractmethod__ = True # Flag that notifies the ABCMeta that is is an actual abstract method. # We provide the original function code and name. callAPI.__code__ = getattr(clazz, name).__code__ callAPI.__name__ = getattr(clazz, name).__name__ updateWrapper(callAPI, getattr(clazz, name)) setattr(clazz, name, callAPI) return clazz
# For the licensing terms see $ROOTSYS/LICENSE. # # For the list of contributors see $ROOTSYS/README/CREDITS. # ################################################################################ import functools from abc import ABCMeta from abc import abstractmethod import ROOT from DistRDF.Backends import Utils from DistRDF.HeadNode import TreeHeadNode # Abstract class declaration # This ensures compatibility between Python 2 and 3 versions, since in # Python 2 there is no ABC class ABC = ABCMeta("ABC", (object, ), {}) class BaseBackend(ABC): """ Base class for RDataFrame distributed backends. Attributes: supported_operations (list): List of operations supported by the backend. initialization (function): Store user's initialization method, if defined. headers (list): List of headers that need to be declared for the analysis. shared_libraries (list): List of shared libraries needed for the analysis.