code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
import argparse import json import os import socket import time import traceback from contextlib import contextmanager from dataclasses import dataclass from io import BufferedReader, BufferedWriter from typing import Dict, Iterator, List, Optional, Tuple import yaml from zuper_commons.logs import ZLoggerInterface from zuper_commons.text import indent from zuper_commons.types import check_isinstance, ZValueError from zuper_ipce import IEDO, IESO, ipce_from_object, object_from_ipce from zuper_nodes import ( ChannelName, InputReceived, InteractionProtocol, LanguageChecker, OutputProduced, Unexpected, ) from zuper_nodes.structures import ( DecodingError, ExternalProtocolViolation, ExternalTimeout, InternalProblem, local_time, NotConforming, TimeSpec, timestamp_from_seconds, TimingInfo, ) from . import logger as logger0, logger_interaction from .constants import ( ATT_CONFIG, CAPABILITY_PROTOCOL_REFLECTION, CTRL_ABORTED, CTRL_CAPABILITIES, CTRL_NOT_UNDERSTOOD, CTRL_OVER, CTRL_UNDERSTOOD, ENV_CONFIG, ENV_DATA_IN, ENV_DATA_OUT, ENV_NAME, ENV_TRANSLATE, KNOWN, TOPIC_ABORTED, ) from .interface import Context from .meta_protocol import ( basic_protocol, BuildDescription, ConfigDescription, NodeDescription, ProtocolDescription, SetConfig, ) from .profiler import Profiler, ProfilerImp from .reading import inputs from .streams import open_for_read, open_for_write from .struct import ControlMessage, RawTopicMessage from .utils import call_if_fun_exists from .writing import Sink iedo = IEDO(True, True) class ConcreteContext(Context): protocol: InteractionProtocol to_write: List[RawTopicMessage] pc: LanguageChecker node_name: str hostname: str tout: Dict[str, str] def __init__( self, sink: Sink, protocol: InteractionProtocol, node_name: str, tout: Dict[str, str], logger: ZLoggerInterface ): self.sink = sink self.protocol = protocol self.pc = LanguageChecker(protocol.interaction) self.node_name = node_name self.hostname = socket.gethostname() self.tout = tout self.to_write = [] self.last_timing = None self.profiler = ProfilerImp() self.logger = logger def get_profiler(self) -> Profiler: return self.profiler def set_last_timing(self, timing: TimingInfo): self.last_timing = timing def get_hostname(self): return self.hostname def write( self, topic: ChannelName, data: object, timing: Optional[TimingInfo] = None, with_schema: bool = False ): self._write(topic, data, timing, with_schema) def _write( self, topic: ChannelName, data: object, timing: Optional[TimingInfo] = None, with_schema: bool = False ) -> None: if topic not in self.protocol.outputs: msg = f'Output channel "{topic}" not found in protocol; know {sorted(self.protocol.outputs)}.' raise Exception(msg) # logger.info(f'Writing output "{topic}".') klass = self.protocol.outputs[topic] if isinstance(klass, type): check_isinstance(data, klass) event = OutputProduced(topic) res = self.pc.push(event) if isinstance(res, Unexpected): msg = f"Unexpected output {topic}: {res}" self.logger.error(msg) return klass = self.protocol.outputs[topic] if isinstance(data, dict): with self.profiler.prof(':serialization'): # noinspection PyTypeChecker data = object_from_ipce(data, klass, iedo=iedo) if timing is None: timing = self.last_timing if timing is not None: s = time.time() if timing.received is None: # XXX time1 = timestamp_from_seconds(s) else: time1 = timing.received.time processed = TimeSpec( time=time1, time2=timestamp_from_seconds(s), frame="epoch", clock=socket.gethostname(), ) timing.processed[self.node_name] = processed timing.received = None topic_o = self.tout.get(topic, topic) ieso = IESO(use_ipce_from_typelike_cache=True, with_schema=with_schema) with self.profiler.prof(':serialization'): data = ipce_from_object(data, ieso=ieso) if timing is not None: with self.profiler.prof(':timing-serialization'): ieso2 = IESO(use_ipce_from_typelike_cache=True, with_schema=False) timing_o = ipce_from_object(timing, ieso=ieso2) else: timing_o = None rtm = RawTopicMessage(topic_o, data, timing_o) self.to_write.append(rtm) def get_to_write(self) -> List[RawTopicMessage]: """ Returns the messages to send and resets the queue""" res = self.to_write self.to_write = [] return res def log(self, s: str): prefix = f"{self.hostname}:{self.node_name}: " self.logger.info(prefix + s) def info(self, s: str): prefix = f"{self.hostname}:{self.node_name}: " self.logger.info(prefix + s) def debug(self, s: str): prefix = f"{self.hostname}:{self.node_name}: " self.logger.debug(prefix + s) def warning(self, s: str): prefix = f"{self.hostname}:{self.node_name}: " self.logger.warning(prefix + s) def error(self, s: str): prefix = f"{self.hostname}:{self.node_name}: " self.logger.error(prefix + s) def get_translation_table(t: str) -> Tuple[Dict[str, str], Dict[str, str]]: tout = {} tin = {} for t in t.split(","): ts = t.split(":") if ts[0] == "in": tin[ts[1]] = ts[2] if ts[0] == "out": tout[ts[1]] = ts[2] return tin, tout def check_variables(): for k, v in os.environ.items(): if k.startswith("AIDONODE") and k not in KNOWN: msg = f'I do not expect variable "{k}" set in environment with value "{v}".' msg += f" I expect: {', '.join(KNOWN)}" logger0.warn(msg) @dataclass class CommContext: fi: BufferedReader fo: BufferedWriter fo_sink: Sink context_meta: ConcreteContext @contextmanager def open_comms(node_name: str, logger_meta: ZLoggerInterface) -> Iterator[CommContext]: data_in = os.environ.get(ENV_DATA_IN, "/dev/stdin") data_out = os.environ.get(ENV_DATA_OUT, "/dev/stdout") fi = open_for_read(data_in) fo = open_for_write(data_out) sink = Sink(fo) context_meta = ConcreteContext( sink=sink, protocol=basic_protocol, node_name=node_name, tout={}, logger=logger_meta ) cc = CommContext(fi, fo, sink, context_meta) try: yield cc except: # sink.write_control_message() context_meta.write(TOPIC_ABORTED, traceback.format_exc()) raise def run_loop(node: object, protocol: InteractionProtocol, args: Optional[List[str]] = None): parser = argparse.ArgumentParser() check_variables() data_in = os.environ.get(ENV_DATA_IN, "/dev/stdin") data_out = os.environ.get(ENV_DATA_OUT, "/dev/stdout") default_name = os.environ.get(ENV_NAME, None) translate = os.environ.get(ENV_TRANSLATE, "") config = os.environ.get(ENV_CONFIG, "{}") parser.add_argument("--data-in", default=data_in) parser.add_argument("--data-out", default=data_out) parser.add_argument("--name", default=default_name) parser.add_argument("--config", default=config) parser.add_argument("--translate", default=translate) parser.add_argument("--loose", default=False, action="store_true") parsed = parser.parse_args(args) tin, tout = get_translation_table(parsed.translate) # expect in:name1:name2, out:name2:name1 fin = parsed.data_in fout = parsed.data_out node_name = parsed.name or type(node).__name__ my_logger = logger0.getChild(node_name) my_logger.debug("run_loop", fin=fin, fout=fout) fi = open_for_read(fin) fo = open_for_write(fout) # logger.name = node_name try: config = yaml.load(config, Loader=yaml.SafeLoader) loop(my_logger, node_name, fi, fo, node, protocol, tin, tout, config=config, fi_desc=fin, fo_desc=fout) except RuntimeError as e: s = str(e).lower() if ("gpu" in s) or ("cuda" in s) or ("CUDA" in s) or ("bailing" in s): raise SystemExit(138) if 'CUDNN_STATUS_INTERNAL_ERROR' in s: raise SystemExit(138) except BaseException as e: if "I need a GPU".lower() in str(e).lower(): raise SystemExit(138) msg = f"Error in node {node_name}" my_logger.error(f"Error in node {node_name}", ET=type(e).__name__, tb=traceback.format_exc()) raise Exception(msg) from e finally: fo.flush() fo.close() fi.close() # noinspection PyBroadException @contextmanager def suppress_exception_logit(): """ Will suppress any exception """ try: yield except BaseException: logger0.error("cannot write sink control messages", bt=traceback.format_exc()) finally: pass # noinspection PyBroadException def loop( logger: ZLoggerInterface, node_name: str, fi: BufferedReader, fo, node: object, protocol: InteractionProtocol, tin: Dict[str, str], tout: Dict[str, str], config: dict, fi_desc: str, fo_desc: str, ): logger.debug(f"Starting reading", fi_desc=fi_desc, fo_desc=fo_desc) initialized = False context_data = None sink = Sink(fo) PASSTHROUGH = (RuntimeError,) logger_data = logger.getChild('data') logger_meta = logger.getChild('meta') try: context_data = ConcreteContext(sink=sink, protocol=protocol, node_name=node_name, tout=tout, logger=logger_data) context_meta = ConcreteContext( sink=sink, protocol=basic_protocol, node_name=node_name + ".wrapper", tout=tout, logger=logger_meta ) wrapper = MetaHandler(node, protocol) for k, v in config.items(): wrapper.set_config(k, v) waiting_for = f"Expecting control message or one of: {context_data.pc.get_expected_events()}" for parsed in inputs(fi, waiting_for=waiting_for): if isinstance(parsed, ControlMessage): expect = [CTRL_CAPABILITIES] if parsed.code not in expect: msg = f'I expect any of {expect}, not "{parsed.code}".' sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg) sink.write_control_message(CTRL_OVER) else: if parsed.code == CTRL_CAPABILITIES: my_capabilities = {"z2": {CAPABILITY_PROTOCOL_REFLECTION: True}} sink.write_control_message(CTRL_UNDERSTOOD) sink.write_control_message(CTRL_CAPABILITIES, my_capabilities) sink.write_control_message(CTRL_OVER) else: assert False elif isinstance(parsed, RawTopicMessage): parsed.topic = tin.get(parsed.topic, parsed.topic) logger_interaction.info(f'Received message of topic "{parsed.topic}".') if parsed.topic.startswith("wrapper."): parsed.topic = parsed.topic.replace("wrapper.", "") receiver0 = wrapper context0 = context_meta else: receiver0 = node context0 = context_data if receiver0 is node and not initialized: try: with context_data.profiler.prof('init'): call_if_fun_exists(node, "init", context=context_data) except PASSTHROUGH: with suppress_exception_logit(): context_meta.write(TOPIC_ABORTED, traceback.format_exc()) raise except BaseException as e: msg = type(e).__name__ msg += '\n' msg = "Exception while calling the node's init() function." msg += '\n' msg += indent(traceback.format_exc(), "| ") with suppress_exception_logit(): context_meta.write(TOPIC_ABORTED, msg) raise InternalProblem(msg) from e # XXX initialized = True if parsed.topic not in context0.protocol.inputs: msg = f'Input channel "{parsed.topic}" not found in protocol. ' msg += f"\n\nKnown channels: {sorted(context0.protocol.inputs)}" with suppress_exception_logit(): sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg) sink.write_control_message(CTRL_OVER) raise ExternalProtocolViolation(msg) sink.write_control_message(CTRL_UNDERSTOOD) try: handle_message_node(parsed, receiver0, context0) to_write = context0.get_to_write() # msg = f'I wrote {len(to_write)} messages.' # logger.info(msg) for rtm in to_write: sink.write_topic_message(rtm.topic, rtm.data, rtm.timing) sink.write_control_message(CTRL_OVER) except PASSTHROUGH: with suppress_exception_logit(): context_meta.write(TOPIC_ABORTED, traceback.format_exc()) raise except BaseException as e: msg = f'Exception while handling a message on topic "{parsed.topic}".' msg += "\n\n" + indent(traceback.format_exc(), "| ") with suppress_exception_logit(): sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise InternalProblem(msg) from e # XXX else: assert False, parsed res = context_data.pc.finish() if isinstance(res, Unexpected): msg = f"Protocol did not finish: {res}" logger_interaction.error(msg) if initialized: try: with context_data.profiler.prof('finish'): call_if_fun_exists(node, "finish", context=context_data) except PASSTHROUGH: context_meta.write(TOPIC_ABORTED, traceback.format_exc()) raise except BaseException as e: msg = "Exception while calling the node's finish() function." msg += "\n\n" + indent(traceback.format_exc(), "| ") context_meta.write(TOPIC_ABORTED, msg) raise InternalProblem(msg) from e # XXX logger.info("benchmark data", stats=context_data.profiler.show_stats()) logger.info("benchmark meta", stats=context_meta.profiler.show_stats()) except BrokenPipeError: msg = "The other side closed communication." logger.info(msg) return except ExternalTimeout as e: msg = "Could not receive any other messages." if context_data: msg += f"\n Expecting one of: {context_data.pc.get_expected_events()}" with suppress_exception_logit(): sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise ExternalTimeout(msg) from e except InternalProblem: raise except BaseException as e: msg = f"Unexpected error:" msg += "\n\n" + indent(traceback.format_exc(), "| ") with suppress_exception_logit(): sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise InternalProblem(msg) from e # XXX class MetaHandler: def __init__(self, node, protocol): self.node = node self.protocol = protocol def set_config(self, key: str, value): if hasattr(self.node, ATT_CONFIG): config = self.node.config if hasattr(config, key): setattr(self.node.config, key, value) else: msg = f"Could not find config key {key}" raise ZValueError(msg, config=config) else: msg = 'Node does not have the "config" attribute.' raise ValueError(msg) def on_received_set_config(self, context, data: SetConfig): key = data.key value = data.value try: self.set_config(key, value) except ValueError as e: context.write("set_config_error", str(e)) else: context.write("set_config_ack", None) def on_received_describe_protocol(self, context): desc = ProtocolDescription(data=self.protocol, meta=basic_protocol) context.write("protocol_description", desc) def on_received_describe_config(self, context): K = type(self.node) if hasattr(K, "__annotations__") and ATT_CONFIG in K.__annotations__: config_type = K.__annotations__[ATT_CONFIG] config_current = getattr(self.node, ATT_CONFIG) else: @dataclass class NoConfig: pass config_type = NoConfig config_current = NoConfig() desc = ConfigDescription(config=config_type, current=config_current) context.write("config_description", desc, with_schema=True) def on_received_describe_node(self, context): desc = NodeDescription(self.node.__doc__) context.write("node_description", desc, with_schema=True) def on_received_describe_build(self, context): desc = BuildDescription() context.write("build_description", desc, with_schema=True) def handle_message_node(parsed: RawTopicMessage, agent, context: ConcreteContext): protocol = context.protocol topic = parsed.topic data = parsed.data pc = context.pc klass = protocol.inputs[topic] with context.profiler.prof(':deserialization'): try: # noinspection PyTypeChecker ob = object_from_ipce(data, klass, iedo=iedo) except BaseException as e: msg = f'Cannot deserialize object for topic "{topic}" expecting {klass}.' try: parsed = json.dumps(parsed, indent=2) except: parsed = str(parsed) msg += "\n\n" + indent(parsed, "|", "parsed: |") raise DecodingError(msg) from e if parsed.timing is not None: timing = object_from_ipce(parsed.timing, TimingInfo, iedo=iedo) else: timing = TimingInfo() timing.received = local_time() context.set_last_timing(timing) # logger.info(f'Before push the state is\n{pc}') event = InputReceived(topic) expected = pc.get_expected_events() res = pc.push(event) # names = pc.get_active_states_names() # logger.info(f'After push of {event}: result \n{res} active {names}' ) if isinstance(res, Unexpected): msg = f'Unexpected input "{topic}": {res}' msg += f"\nI expected: {expected}" msg += f"\n {pc}" context.error(msg) raise ExternalProtocolViolation(msg) else: expect_fn = f"on_received_{topic}" with context.profiler.prof(topic): call_if_fun_exists(agent, expect_fn, data=ob, context=context, timing=timing) def check_implementation(node, protocol: InteractionProtocol): logger0.debug("checking implementation") for n in protocol.inputs: expect_fn = f"on_received_{n}" if not hasattr(node, expect_fn): msg = f"The class {type(node).__name__} misses the function {expect_fn}" msg += f"\nI know {sorted(_ for _ in type(node).__dict__ if _.startswith('on'))}" raise NotConforming(msg) for x in type(node).__dict__: if x.startswith("on_received_"): input_name = x.replace("on_received_", "") if input_name not in protocol.inputs: msg = f'The node has function "{x}" but there is no input "{input_name}".' raise NotConforming(msg) logger0.debug("checking implementation OK")
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/wrapper.py
wrapper.py
import os import stat import time from io import BufferedReader from zuper_commons.fs import make_sure_dir_exists from . import logger, logger_interaction def wait_for_creation(fn: str, wait: float = 3.0): t0 = time.time() if os.path.exists(fn): # logger.info(f"Found {fn} right away.") return while not os.path.exists(fn): time.sleep(wait) dt = int(time.time() - t0) msg = f"Waiting for creation of {fn} since {dt} seconds." logger.debug(msg) dt = int(time.time() - t0) logger.debug(f"Found {fn} after {dt} seconds waiting.") def open_for_read(fin: str, timeout: float = None) -> BufferedReader: t0 = time.time() # first open reader file in case somebody is waiting for it if os.path.exists(fin): logger_interaction.info(f"Found file {fin} right away") else: while not os.path.exists(fin): delta = time.time() - t0 if timeout is not None and (delta > timeout): msg = f"The file {fin!r} was not created before {timeout:.1f} seconds. I give up." raise EnvironmentError(msg) logger_interaction.info(f"waiting for file {fin} to be created since {int(delta)} seconds.") time.sleep(1) delta = time.time() - t0 logger_interaction.info(f"Waited for file {fin} for a total of {int(delta)} seconds") logger_interaction.info(f"Opening input {fin} for reading.") fi = open(fin, "rb", buffering=0) # noinspection PyTypeChecker fi = BufferedReader(fi, buffer_size=1) return fi def open_for_write(fout: str): if fout == "/dev/stdout": logger_interaction.info("Opening stdout for writing") return open("/dev/stdout", "wb", buffering=0) else: wants_fifo = fout.startswith("fifo:") fout = fout.replace("fifo:", "") logger_interaction.info(f"Opening output file {fout} (wants fifo: {wants_fifo})") if not os.path.exists(fout): if wants_fifo: make_sure_dir_exists(fout) os.mkfifo(fout) logger_interaction.info(f"Fifo {fout} created.") else: is_fifo = stat.S_ISFIFO(os.stat(fout).st_mode) if wants_fifo and not is_fifo: logger_interaction.info(f"Recreating {fout} as a fifo.") os.unlink(fout) os.mkfifo(fout) if wants_fifo: logger_interaction.info(f"Fifo {fout} created. Opening will block until a reader appears.") logger.debug(f"Fifo {fout} created. I will block until a reader appears.") make_sure_dir_exists(fout) fo = open(fout, "wb", buffering=0) logger.debug(f"Fifo reader appeared for {fout}.") if wants_fifo: logger_interaction.info(f"A reader has connected to my fifo {fout}") return fo
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/streams.py
streams.py
import time from abc import ABC, abstractmethod from collections import defaultdict from contextlib import contextmanager from dataclasses import dataclass from typing import ContextManager, Dict, List, Optional, Tuple __all__ = ['ProfilerImp', 'Profiler', 'fake_profiler'] from zuper_commons.types import ZException @dataclass class FinishedIteration: dt: float @dataclass class Iteration: tname: str children: "Dict[str, List[FinishedIteration]]" class Profiler(ABC): @abstractmethod def prof(self, s: str) -> ContextManager[None]: yield @abstractmethod def show_stats(self, prefix: Optional[Tuple[str, ...]] = None) -> str: pass class ProfilerImp(Profiler): context: List[Iteration] stats: Dict[Tuple[str, ...], List[float]] def __init__(self): self.context = [Iteration('root', defaultdict(list))] self.stats = defaultdict(list) self.t0 = time.time() @contextmanager def prof(self, s: str): it = Iteration(s, defaultdict(list)) self.context.append(it) current_context = list(self.context) my_id = tuple(_.tname for _ in current_context) t0 = time.time() yield self.context.pop() dt = time.time() - t0 s = '/'.join(my_id) if self.context: last = self.context[-1] last.children[s].append(FinishedIteration(dt)) if it.children: explained = sum(sum(x.dt for x in _) for _ in it.children.values()) unexplained = dt - explained # perc = int(100 * unexplained / dt) # logger.debug(f'timer: {dt:10.4f} {s} / {unexplained:.4f} {perc}% unexp ') self.stats[my_id + ('self',)].append(unexplained) else: pass # logger.debug(f'timer: {dt:10.4f} {s}') self.stats[my_id].append(dt) def show_stats(self, prefix: Tuple[str, ...] = ('root',)) -> str: # logger.info(str(list(self.stats))) tottime = time.time() - self.t0 lines = self.show_stats_(prefix, 1, tottime) if not lines: lines.append(f'Could not find any *completed* children for prefix {prefix}.') # raise ZException(msg, prefix=prefix, lines=lines, # known=list(self.stats)) return "\n".join(lines) def show_stats_(self, prefix: Tuple[str, ...], ntot: int, tottime: float) -> List[str]: # logger.info(f'Searching while {prefix}') lines = [] for k, v in self.stats.items(): if k[:len(prefix)] != prefix: # logger.info(f'excluding {k}') continue if len(k) == len(prefix) + 1: n = len(v) total = sum(v) rn = n / ntot dt = total / n perc = 100 * total / tottime s = f'┌ {perc:4.1f}% ' + k[-1] + f' {dt:6.3f}' if rn != 1: s += f' {rn:6.1f}x' lines.append(s) for _ in self.show_stats_(prefix=k, ntot=n, tottime=total): lines.append('│ ' + _) # else: # logger.info(f'excluding {k} not child') # logger.info(f'lines for {prefix}: {lines}') return lines class FakeProfiler(Profiler): @contextmanager def prof(self, s: str): yield def show_stats(self, prefix: Optional[Tuple[str, ...]] = None) -> str: return '(fake)' fake_profiler = FakeProfiler()
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/profiler.py
profiler.py
import cbor2 from .constants import CUR_PROTOCOL, FIELD_COMPAT, FIELD_CONTROL, FIELD_DATA, FIELD_TIMING, FIELD_TOPIC __all__ = ["Sink"] class Sink: def __init__(self, of): self.of = of def write_topic_message(self, topic: str, data: object, timing): """ Can raise BrokenPipeError""" m = {} m[FIELD_COMPAT] = [CUR_PROTOCOL] m[FIELD_TOPIC] = topic m[FIELD_DATA] = data m[FIELD_TIMING] = timing self._write_raw(m) def write_control_message(self, code, data: object = None): """ Can raise BrokenPipeError""" m = {} m[FIELD_CONTROL] = code m[FIELD_DATA] = data self._write_raw(m) def _write_raw(self, m: dict): """ Can raise BrokenPipeError""" j = cbor2.dumps(m) self.of.write(j) self.of.flush()
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/writing.py
writing.py
from dataclasses import dataclass from typing import Generic, NewType, Optional, TypeVar from zuper_nodes.structures import TimingInfo from .constants import FIELD_CONTROL, FIELD_DATA X = TypeVar("X") __all__ = ['MsgReceived', 'RawTopicMessage', 'ControlMessage', 'WireMessage', 'Malformed','interpret_control_message'] @dataclass class MsgReceived(Generic[X]): topic: str data: X timing: TimingInfo @dataclass class RawTopicMessage: topic: str data: Optional[dict] timing: Optional[dict] @dataclass class ControlMessage: code: str msg: Optional[str] WireMessage = NewType("WireMessage", dict) class Malformed(Exception): pass def interpret_control_message(m: WireMessage) -> ControlMessage: if not isinstance(m, dict): msg = f"Expected dictionary, not {type(m)}." raise Malformed(msg) if not FIELD_CONTROL in m: msg = f"Expected field {FIELD_CONTROL}, obtained {list(m)}." raise Malformed(msg) code = m[FIELD_CONTROL] msg = m.get(FIELD_DATA, None) return ControlMessage(code, msg)
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/struct.py
struct.py
import inspect from zuper_commons.types import ZTypeError from . import logger __all__ = ["call_if_fun_exists"] def call_if_fun_exists(ob, fname, **kwargs): kwargs = dict(kwargs) if not hasattr(ob, fname): msg = f"Missing function {fname}() for {type(ob)}" logger.warning(msg) return f = getattr(ob, fname) a = inspect.getfullargspec(f) for k, v in dict(kwargs).items(): if k not in a.args: kwargs.pop(k) try: f(**kwargs) except TypeError as e: msg = f"Cannot call function {f}." raise ZTypeError(msg, f=f, args=kwargs, argspec=a) from e
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/utils.py
utils.py
from dataclasses import dataclass from typing import Any, Dict, List from zuper_nodes import InteractionProtocol @dataclass class SetConfig: key: str value: Any @dataclass class ConfigDescription: config: type current: Any @dataclass class NodeDescription: description: str @dataclass class BuildDescription: pass @dataclass class ProtocolDescription: data: InteractionProtocol meta: InteractionProtocol @dataclass class CommsHealth: # ignored because not compatible ignored: Dict[str, int] # unexpected topics unexpected: Dict[str, int] # malformed data malformed: Dict[str, int] # if we are completely lost unrecoverable_protocol_error: bool @dataclass class NodeHealth: # there is a critical error that makes it useless to continue critical: bool # severe problem but we can continue severe: bool # a minor problem to report minor: bool details: str LogEntry = str basic_protocol = InteractionProtocol( description="""\ Basic interaction protocol for nodes spoken by the node wrapper. """, inputs={ "describe_config": type(None), "set_config": SetConfig, "describe_protocol": type(None), "describe_node": type(None), "describe_build": type(None), "get_state": type(None), "set_state": Any, "get_logs": type(None), }, language="""\ ( (in:describe_config ; out:config_description) | (in:set_config ; (out:set_config_ack | out:set_config_error)) | (in:describe_protocol ; out:protocol_description) | (in:describe_node ; out:node_description) | (in:describe_build ; out:build_description) | (in:get_state ; out:node_state) | (in:set_state ; (out:set_state_ack| out:set_state_error) ) | (in:get_logs ; out:logs) | out:aborted )* """, outputs={ "config_description": ConfigDescription, "set_config_ack": type(None), "set_config_error": str, "protocol_description": ProtocolDescription, "node_description": NodeDescription, "build_description": BuildDescription, "node_state": Any, "set_state_ack": type(None), "set_state_error": str, "logs": List[LogEntry], "aborted": str, }, )
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/meta_protocol.py
meta_protocol.py
import sys from abc import ABC, ABCMeta, abstractmethod from typing import List, Optional from zuper_commons.logs import monkeypatch_findCaller from zuper_nodes.structures import TimingInfo from zuper_typing import PYTHON_36, PYTHON_37 from .profiler import Profiler __all__ = [ "Context", "wrap_direct", ] def wrap_direct(node, protocol, args: Optional[List[str]] = None): if args is None: args = sys.argv[1:] from .wrapper import check_implementation, run_loop if PYTHON_36 or PYTHON_37: monkeypatch_findCaller() check_implementation(node, protocol) run_loop(node, protocol, args) class Context(ABC): @abstractmethod def write( self, topic: str, data: object, timing: TimingInfo = None, with_schema: bool = False, ): pass @abstractmethod def info(self, msg: str): pass @abstractmethod def debug(self, msg: str): pass @abstractmethod def warning(self, msg: str): pass @abstractmethod def error(self, msg: str): pass @abstractmethod def get_hostname(self): pass @abstractmethod def get_profiler(self) -> Profiler: pass
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/interface.py
interface.py
import os from io import BufferedReader from typing import cast, List, Optional import cbor2 as cbor from zuper_commons.text import indent from zuper_commons.types import ZException from zuper_ipce import IEDO, IESO, ipce_from_object, object_from_ipce from zuper_ipce.json2cbor import read_next_cbor from zuper_nodes import ( check_compatible_protocol, ExternalNodeDidNotUnderstand, ExternalProtocolViolation, ExternalTimeout, InteractionProtocol, RemoteNodeAborted, TimingInfo, ) from . import logger, logger_interaction from .constants import ( CAPABILITY_PROTOCOL_REFLECTION, CTRL_ABORTED, CTRL_CAPABILITIES, CTRL_NOT_UNDERSTOOD, CTRL_OVER, CTRL_UNDERSTOOD, CUR_PROTOCOL, FIELD_COMPAT, FIELD_CONTROL, FIELD_DATA, FIELD_TIMING, FIELD_TOPIC, TAG_Z2, TOPIC_ABORTED, ) from .meta_protocol import basic_protocol, ProtocolDescription from .profiler import fake_profiler, Profiler from .streams import wait_for_creation from .struct import interpret_control_message, MsgReceived, WireMessage __all__ = ["ComponentInterface", "MsgReceived", "read_reply"] iedo = IEDO(True, True) class ComponentInterface: node_protocol: Optional[InteractionProtocol] data_protocol: Optional[InteractionProtocol] nreceived: int expect_protocol: Optional[InteractionProtocol] def __init__( self, fnin: str, fnout: str, expect_protocol: Optional[InteractionProtocol], nickname: str, timeout=None, ): self.nickname = nickname self._cc = None try: os.mkfifo(fnin) except BaseException as e: msg = f"Cannot create fifo {fnin}" raise Exception(msg) from e ### FIXME: this is blocking, throw exception self.fpin = open(fnin, "wb", buffering=0) wait_for_creation(fnout) self.fnout = fnout f = open(fnout, "rb", buffering=0) # noinspection PyTypeChecker self.fpout = BufferedReader(f, buffer_size=1) self.nreceived = 0 self.expect_protocol = expect_protocol self.node_protocol = None self.data_protocol = None self.timeout = timeout def close(self): self.fpin.close() self.fpout.close() def cc(self, f): """ CC-s everything that is read or written to this file. """ self._cc = f def _get_node_protocol(self, timeout: float = None): """ raises ExternalProtocolViolation, indirectly IncompatibleProtocol :param timeout: :return: """ self.my_capabilities = {TAG_Z2: {CAPABILITY_PROTOCOL_REFLECTION: True}} msg = {FIELD_CONTROL: CTRL_CAPABILITIES, FIELD_DATA: self.my_capabilities} j = self._serialize(msg) self._write(j) msgs = read_reply( self.fpout, timeout=timeout, waiting_for=f"Reading {self.nickname} capabilities", nickname=self.nickname, ) self.node_capabilities = msgs[0]["data"] # logger.info("My capabilities: %s" % self.my_capabilities) # logger.info("Found capabilities: %s" % self.node_capabilities) if TAG_Z2 not in self.node_capabilities: msg = f"Incompatible node; capabilities {self.node_capabilities}" raise ExternalProtocolViolation(msg) z = self.node_capabilities[TAG_Z2] if not z.get(CAPABILITY_PROTOCOL_REFLECTION, False): logger.debug("Node does not support reflection.") if self.expect_protocol is None: msg = "Node does not support reflection - need to provide protocol." raise Exception(msg) else: ob: MsgReceived[ProtocolDescription] ob = self.write_topic_and_expect( "wrapper.describe_protocol", expect="protocol_description", timeout=timeout, ) self.node_protocol = ob.data.data self.data_protocol = ob.data.meta if self.expect_protocol is not None: check_compatible_protocol(self.node_protocol, self.expect_protocol) def write_topic_and_expect( self, topic: str, data=None, with_schema: bool = False, timeout: float = None, timing=None, expect: str = None, profiler: Profiler = fake_profiler ) -> MsgReceived: timeout = timeout or self.timeout with profiler.prof(f':write-{topic}'): self._write_topic(topic, data=data, with_schema=with_schema, timing=timing, profiler=profiler) with profiler.prof(f':write-{topic}-expect-{expect}'): ob: MsgReceived = self.read_one(expect_topic=expect, timeout=timeout, profiler=profiler) return ob def write_topic_and_expect_zero( self, topic: str, data=None, with_schema=False, timeout=None, timing=None, profiler: Profiler = fake_profiler ): timeout = timeout or self.timeout with profiler.prof(f':write-{topic}'): self._write_topic(topic, data=data, with_schema=with_schema, timing=timing, profiler=profiler) with profiler.prof(f':write-{topic}-wait-reply'): msgs = read_reply(self.fpout, timeout=timeout, nickname=self.nickname) if msgs: msg = f"Expecting zero, got {msgs}" raise ExternalProtocolViolation(msg) def _write_topic(self, topic: str, data=None, with_schema: bool = False, timing=None, profiler: Profiler = fake_profiler): suggest_type = object if self.node_protocol: if topic in self.node_protocol.inputs: suggest_type = self.node_protocol.inputs[topic] ieso = IESO(with_schema=with_schema) ieso_true = IESO(with_schema=True) with profiler.prof(':serialization'): ipce = ipce_from_object(data, suggest_type, ieso=ieso) # try to re-read if suggest_type is not object: try: with profiler.prof(':double-check'): _ = object_from_ipce(ipce, suggest_type, iedo=iedo) except BaseException as e: msg = ( f'While attempting to write on topic "{topic}", cannot ' f"interpret the value as {suggest_type}.\nValue: {data}" ) raise ZException(msg, data=data, ipce=ipce, suggest_type=suggest_type) from e # XXX msg = { FIELD_COMPAT: [CUR_PROTOCOL], FIELD_TOPIC: topic, FIELD_DATA: ipce, FIELD_TIMING: timing, } with profiler.prof(':cbor-dump1'): j = self._serialize(msg) with profiler.prof(':write'): self._write(j) # make sure we write the schema when we copy it if not with_schema: with profiler.prof(':re-serializing-for-log'): msg[FIELD_DATA] = ipce_from_object(data, ieso=ieso_true) with profiler.prof(':cbor-dump2'): j = self._serialize(msg) if self._cc: with profiler.prof(':write-cc'): self._cc.write(j) self._cc.flush() logger_interaction.info(f'Written to topic "{topic}" >> {self.nickname}.') def _write(self, j): try: self.fpin.write(j) self.fpin.flush() except BrokenPipeError as e: msg = ( f'While attempting to write to node "{self.nickname}", ' f"I reckon that the pipe is closed and the node exited." ) try: received = self.read_one(expect_topic=TOPIC_ABORTED) if received.topic == TOPIC_ABORTED: msg += "\n\nThis is the aborted message:" msg += "\n\n" + indent(received.data, " |") except BaseException as e2: msg += f"\n\nI could not read any aborted message: {e2}" raise RemoteNodeAborted(msg) from e def _serialize(self, msg: object) -> bytes: j = cbor.dumps(msg) return j def read_one(self, expect_topic: str = None, timeout: float = None, profiler: Profiler = fake_profiler) -> MsgReceived: timeout = timeout or self.timeout try: if expect_topic: waiting_for = f'Expecting topic "{expect_topic}" << {self.nickname}.' else: waiting_for = None msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for, nickname=self.nickname, profiler=profiler) if len(msgs) == 0: msg = f'Expected one message from node "{self.nickname}". Got zero.' if expect_topic: msg += f'\nExpecting topic "{expect_topic}".' raise ExternalProtocolViolation(msg) if len(msgs) > 1: msg = f"Expected only one message. Got {msgs}" raise ExternalProtocolViolation(msg) msg = msgs[0] if FIELD_TOPIC not in msg: m = f'Invalid message does not contain the field "{FIELD_TOPIC}".' m += f"\n {msg}" raise ExternalProtocolViolation(m) topic = msg[FIELD_TOPIC] if expect_topic: if topic != expect_topic: msg = f'I expected topic "{expect_topic}" but received "{topic}".' raise ExternalProtocolViolation(msg) if topic in basic_protocol.outputs: klass = basic_protocol.outputs[topic] else: if self.node_protocol: if topic not in self.node_protocol.outputs: msg = f'Cannot find topic "{topic}" in outputs of detected node protocol.' msg += f"\nI know: {sorted(self.node_protocol.outputs)}" raise ExternalProtocolViolation(msg) else: klass = self.node_protocol.outputs[topic] else: if not topic in self.expect_protocol.outputs: msg = f'Cannot find topic "{topic}".' raise ExternalProtocolViolation(msg) else: klass = self.expect_protocol.outputs[topic] data = object_from_ipce(msg[FIELD_DATA], klass, iedo=iedo) ieso_true = IESO(with_schema=True) if self._cc: # need to revisit this msg[FIELD_DATA] = ipce_from_object(data, ieso=ieso_true) msg_b = self._serialize(msg) self._cc.write(msg_b) self._cc.flush() if FIELD_TIMING not in msg: timing = TimingInfo() else: timing = object_from_ipce(msg[FIELD_TIMING], TimingInfo, iedo=iedo) self.nreceived += 1 return MsgReceived[klass](topic, data, timing) except StopIteration as e: msg = f"EOF detected on {self.fnout} after {self.nreceived} messages." if expect_topic: msg += f' Expected topic "{expect_topic}".' raise StopIteration(msg) from e except TimeoutError as e: msg = f"Timeout detected on {self.fnout} after {self.nreceived} messages." if expect_topic: msg += f' Expected topic "{expect_topic}".' raise ExternalTimeout(msg) from e def read_reply(fpout, nickname: str, timeout: float = None, waiting_for: str = None, profiler: Profiler = fake_profiler) -> List: """ Reads a control message. Returns if it is CTRL_UNDERSTOOD. Raises: ExternalTimeout RemoteNodeAborted ExternalNodeDidNotUnderstand ExternalProtocolViolation otherwise. """ try: with profiler.prof(':read_next_cbor'): c = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for) wm = cast(WireMessage, c) # logger.debug(f'{nickname} sent {wm}') except TimeoutError: msg = f"Timeout of {timeout} violated while waiting for {waiting_for!r}." raise ExternalTimeout(msg) from None except StopIteration: msg = f"Remote node closed communication ({waiting_for})" raise RemoteNodeAborted(msg) from None cm = interpret_control_message(wm) if cm.code == CTRL_UNDERSTOOD: with profiler.prof(':read_until_over'): others = read_until_over(fpout, timeout=timeout, nickname=nickname) return others elif cm.code == CTRL_ABORTED: msg = f'The remote node "{nickname}" aborted with the following error:' msg += "\n\n" + indent(cm.msg, "|", f"error in {nickname} |") raise RemoteNodeAborted(msg) elif cm.code == CTRL_NOT_UNDERSTOOD: _others = read_until_over(fpout, timeout=timeout, nickname=nickname) msg = f'The remote node "{nickname}" reports that it did not understand the message:' msg += "\n\n" + indent(cm.msg, "|", f"reported by {nickname} |") raise ExternalNodeDidNotUnderstand(msg) else: msg = f"Remote node raised unknown code {cm}: {cm.code}" raise ExternalProtocolViolation(msg) def read_until_over(fpout, timeout: float, nickname: str) -> List[WireMessage]: """ Raises RemoteNodeAborted, ExternalTimeout """ res = [] waiting_for = f"Reading reply of {nickname}." while True: try: c = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for) wm = cast(WireMessage, c) if wm.get(FIELD_CONTROL, "") == CTRL_ABORTED: m = f'External node "{nickname}" aborted:' m += "\n\n" + indent(wm.get(FIELD_DATA, None), "|", f"error in {nickname} |") raise RemoteNodeAborted(m) if wm.get(FIELD_CONTROL, "") == CTRL_OVER: # logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res)) break # logger.info(f'Node "{nickname}" sent %s.' % len(wm)) except StopIteration: msg = f'External node "{nickname}" closed communication.' raise RemoteNodeAborted(msg) from None except TimeoutError: msg = f'Timeout while reading output of node "{nickname}" after {timeout} s.' raise ExternalTimeout(msg) from None res.append(wm) return res
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/wrapper_outside.py
wrapper_outside.py
import logging from zuper_commons.logs import ZLogger logger = ZLogger(__name__) logger.setLevel(logging.DEBUG) logger_interaction = logger.getChild("interaction") logger_interaction.setLevel(logging.CRITICAL) from .interface import * from .struct import * from .profiler import *
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/__init__.py
__init__.py
import time from typing import Iterator, Optional, Union import select from zuper_commons.text import indent from zuper_ipce.json2cbor import read_next_cbor from zuper_nodes.structures import ExternalTimeout from . import logger from .constants import CUR_PROTOCOL, FIELD_COMPAT, FIELD_CONTROL, FIELD_DATA, FIELD_TIMING, FIELD_TOPIC from .struct import ControlMessage, interpret_control_message, RawTopicMessage, WireMessage M = Union[RawTopicMessage, ControlMessage] def inputs(f, give_up: Optional[float] = None, waiting_for: str = None) -> Iterator[M]: last = time.time() intermediate_timeout = 3.0 intermediate_timeout_multiplier = 1.5 while True: readyr, readyw, readyx = select.select([f], [], [f], intermediate_timeout) if readyr: try: parsed = read_next_cbor(f, waiting_for=waiting_for) except StopIteration: return if not isinstance(parsed, dict): msg = f"Expected a dictionary, obtained {parsed!r}" logger.error(msg) continue if FIELD_CONTROL in parsed: m = interpret_control_message(WireMessage(parsed)) yield m elif FIELD_TOPIC in parsed: if not FIELD_COMPAT in parsed: msg = f'Could not find field "compat" in structure "{parsed}".' logger.error(msg) continue l = parsed[FIELD_COMPAT] if not isinstance(l, list): msg = f"Expected a list for compatibility value, found {l!r}" logger.error(msg) continue if not CUR_PROTOCOL in parsed[FIELD_COMPAT]: msg = f"Skipping message because could not find {CUR_PROTOCOL} in {l}." logger.warn(msg) continue rtm = RawTopicMessage( parsed[FIELD_TOPIC], parsed.get(FIELD_DATA, None), parsed.get(FIELD_TIMING, None), ) yield rtm elif readyx: logger.warning(f"Exceptional condition on input channel {readyx}") else: delta = time.time() - last if give_up is not None and (delta > give_up): msg = f"I am giving up after {delta:.1f} seconds." raise ExternalTimeout(msg) else: intermediate_timeout *= intermediate_timeout_multiplier msg = f"Input channel not ready after {delta:.1f} seconds. Will re-try." if waiting_for: msg += "\n" + indent(waiting_for, "> ") msg += f"\n I will warn again in {intermediate_timeout:.1f} seconds." logger.warning(msg)
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/reading.py
reading.py
import argparse import dataclasses import subprocess import sys from dataclasses import dataclass from io import BufferedReader, BytesIO from typing import cast import cbor2 import yaml from zuper_commons.text import indent from zuper_ipce import object_from_ipce from zuper_ipce.json2cbor import read_cbor_or_json_objects from zuper_nodes import InteractionProtocol from . import logger from .meta_protocol import ( BuildDescription, ConfigDescription, NodeDescription, ProtocolDescription, ) def identify_main(): usage = None parser = argparse.ArgumentParser(usage=usage) parser.add_argument("--image", default=None) parser.add_argument("--command", default=None) parsed = parser.parse_args() image = parsed.image if image is not None: ni: NodeInfo = identify_image2(image) elif parsed.command is not None: command = parsed.command.split() ni: NodeInfo = identify_command(command) else: msg = "Please specify either --image or --command" logger.error(msg) sys.exit(1) print("\n\n") print(indent(describe_nd(ni.nd), "", "desc: ")) print("\n\n") print(indent(describe_bd(ni.bd), "", "build: ")) print("\n\n") print(indent(describe_cd(ni.cd), "", "config: ")) print("\n\n") print(indent(describe(ni.pd.data), "", "data: ")) print("\n\n") print(indent(describe(ni.pd.meta), "", "meta: ")) def describe_nd(nd: NodeDescription): return str(nd.description) def describe_bd(nd: BuildDescription): return str(nd) def describe_cd(nd: ConfigDescription): s = [] # noinspection PyDataclass for f in dataclasses.fields(nd.config): # for k, v in nd.config.__annotations__.items(): s.append(f"{f.name:>20}: {f.type} = {f.default}") if not s: return "No configuration switches available." if hasattr(nd.config, "__doc__"): s.insert(0, nd.config.__doc__) return "\n".join(s) def describe(ip: InteractionProtocol): s = "InteractionProtocol" s += "\n\n" + "* Description:" s += "\n\n" + indent(ip.description.strip(), " ") s += "\n\n" + "* Inputs:" for name, type_ in ip.inputs.items(): s += f"\n {name:>25}: {type_}" s += "\n\n" + "* Outputs:" for name, type_ in ip.outputs.items(): s += f"\n {name:>25}: {type_}" s += "\n\n" + "* Language:" s += "\n\n" + ip.language return s @dataclass class NodeInfo: pd: ProtocolDescription nd: NodeDescription bd: BuildDescription cd: ConfigDescription def identify_command(command) -> NodeInfo: d = [ {"topic": "wrapper.describe_protocol"}, {"topic": "wrapper.describe_config"}, {"topic": "wrapper.describe_node"}, {"topic": "wrapper.describe_build"}, ] to_send = b"" for p in d: p["compat"] = ["aido2"] # to_send += (json.dumps(p) + '\n').encode('utf-8') to_send += cbor2.dumps(p) cp = subprocess.run(command, input=to_send, capture_output=True) s = cp.stderr.decode("utf-8") sys.stderr.write(indent(s.strip(), "|", " stderr: |") + "\n\n") # noinspection PyTypeChecker f = BufferedReader(BytesIO(cp.stdout)) stream = read_cbor_or_json_objects(f) res = stream.__next__() logger.debug(yaml.dump(res)) pd = cast(ProtocolDescription, object_from_ipce(res["data"], ProtocolDescription)) res = stream.__next__() logger.debug(yaml.dump(res)) cd = cast(ConfigDescription, object_from_ipce(res["data"], ConfigDescription)) res = stream.__next__() logger.debug(yaml.dump(res)) nd = cast(NodeDescription, object_from_ipce(res["data"], NodeDescription)) res = stream.__next__() logger.debug(yaml.dump(res)) bd = cast(BuildDescription, object_from_ipce(res["data"], BuildDescription)) logger.debug(yaml.dump(res)) return NodeInfo(pd, nd, bd, cd) def identify_image2(image) -> NodeInfo: cmd = ["docker", "run", "--rm", "-i", image] return identify_command(cmd) # def identify_image(image): # import docker # client = docker.from_env() # # # container: Container = client.containers.create(image, detach=True, stdin_open=True) # print(container) # # time.sleep(4) # # attach to the container stdin socket # container.start() # # s = container.exec_run() # s: SocketIO = container.attach_socket(params={'stdin': 1, 'stream': 1, 'stderr': 0, 'stdout': 0}) # s_out: SocketIO = container.attach_socket(params={ 'stream': 1, 'stdout': 1, 'stderr': 0, 'stdin': 0}) # s_stderr: SocketIO = container.attach_socket(params={'stream': 1, 'stdout': 0, 'stderr': 1, 'stdin': 0}) # print(s.__dict__) # print(s_out.__dict__) # # send text # # s.write(j) # os.write(s._sock.fileno(), j) # os.close(s._sock.fileno()) # s._sock.close() # # s.close() # # f = os.fdopen(s_out._sock.fileno(), 'rb') # # there is some garbage: b'\x01\x00\x00\x00\x00\x00\x1e|{ # f.read(8) # # for x in read_cbor_or_json_objects(f): # print(x) # print(f.read(10)) # # print(os.read(s_out._sock.fileno(), 100)) # # print(os.read(s_stderr._sock.fileno(), 100)) # # close, stop and disconnect # s.close()
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/identify.py
identify.py
import argparse import os import sys import traceback from dataclasses import dataclass, field from typing import Dict, Optional import yaml from zuper_commons.types import import_name from zuper_ipce import object_from_ipce from zuper_typing import debug_print from . import logger from zuper_nodes_wrapper.constants import CTRL_ABORTED, CTRL_OVER from zuper_nodes_wrapper.wrapper import CommContext, open_comms from .interface import wrap_direct __all__ = ['launcher_main'] @dataclass class NodeLaunchConfig: node: str protocol: str config: Dict[str, object] = field(default_factory=dict) # noinspection PyBroadException def launcher_main(): sys.path.append(os.getcwd()) prog = 'node-launch' parser = argparse.ArgumentParser(prog=prog) # define arguments parser.add_argument( "--config", required=True, help="Config file (node_launch.yaml)", ) parser.add_argument( "--protocol", help="Protocol (python symbol)", ) parser.add_argument( "--node", help="node class (python symbol)", ) parser.add_argument( "--check", default=False, action='store_true', help="only check symbols importable" ) # parse arguments parsed = parser.parse_args() errors = [] node_type = None node = None config:Optional[NodeLaunchConfig] = None def complain(m: str, **kwargs): er = m, kwargs logger.error(er[0], **er[1]) errors.append(er) if parsed.config: if not os.path.exists(parsed.config): msg = f'Cannot find path {parsed.config}' complain(msg) else: try: with open(parsed.config) as f: data = f.read() y = yaml.load(data, Loader=yaml.Loader) config = object_from_ipce(y, NodeLaunchConfig) except Exception: msg = f'Cannot load config file {parsed.config}' complain(msg, tb=traceback.format_exc()) else: node_symbol = parsed.node protocol_symbol = parsed.protocol if node_symbol is None or protocol_symbol is None: msg = 'Either specify --config or both --node and --protocol' complain(msg) else: config = NodeLaunchConfig(node=node_symbol, protocol=protocol_symbol, config={}) protocol = None sys.path.append(os.getcwd()) if not errors: try: node_type = import_name(config.node) except Exception: msg = 'Cannot import the node class' complain(msg, node_symbol=config.node, tb=traceback.format_exc()) if parsed.check: if errors: logger.error('Check not passed') sys.exit(1) else: logger.info('Check passed') sys.exit(0) if not errors: try: # noinspection PyCallingNonCallable node = node_type() except Exception: msg = 'Cannot instantiate the node class' complain(msg, node_symbol=config.node, node_type=node_type, tb=traceback.format_exc()) if not errors: try: protocol = import_name(config.protocol) except Exception: msg = 'Cannot import the protocol class' complain(msg, protocol_symbol=config.protocol, tb=traceback.format_exc()) if not errors: return wrap_direct(node=node, protocol=protocol, args=[]) else: cc: CommContext with open_comms('unnamed', logger_meta=logger) as cc: msg = debug_print(errors) cc.fo_sink.write_control_message(CTRL_ABORTED, msg) cc.fo_sink.write_control_message(CTRL_OVER) if __name__ == '__main__': launcher_main()
zuper-nodes-z6
/zuper-nodes-z6-6.2.17.tar.gz/zuper-nodes-z6-6.2.17/src/zuper_nodes_wrapper/launcher.py
launcher.py
from setuptools import setup import sys if not sys.version_info >= (3, 6, 0): msg = 'Unsupported version %s' % sys.version raise Exception(msg) def get_version(filename): import ast version = None with open(filename) as f: for line in f: if line.startswith('__version__'): version = ast.parse(line).body[0].value.s break else: raise ValueError('No version found in %r.' % filename) if version is None: raise ValueError(filename) return version version = get_version(filename='src/zuper_nodes/__init__.py') setup( name='zuper-nodes', version=version, keywords='', package_dir={'': 'src'}, packages=[ 'zuper_nodes', 'zuper_nodes_tests', 'zuper_nodes_wrapper', 'zuper_nodes_wrapper_tests', ], install_requires=[ 'compmake', 'pyparsing', 'PyContracts', 'pyparsing', 'PyContracts', 'networkx', 'termcolor', 'zuper-utils', 'cbor2', 'base58', ], entry_points={ 'console_scripts': [ 'zuper-node-identify=zuper_nodes_wrapper.identify:identify_main', ], }, )
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/setup.py
setup.py
from comptests import comptest, run_module_tests @comptest def dummy1(): pass @comptest def dummy2(): pass @comptest def dummy3(): pass @comptest def dummy4(): pass @comptest def dummy5(): pass if __name__ == '__main__': run_module_tests()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_tests/test1.py
test1.py
from nose.tools import assert_equal from zuper_nodes import Language, ExpectInputReceived, ExpectOutputProduced, InSequence, ZeroOrMore, ZeroOrOne, \ OneOrMore, Either from zuper_nodes.language_parse import Syntax from comptests import comptest from contracts import check_isinstance def parse_language(s: str) -> Language: expr = Syntax.language res = expr.parseString(s, parseAll=True) res = res[0] return res def expect_parse(expr, s, expected): check_isinstance(s, str) check_isinstance(expected, (type(None), Language)) res = expr.parseString(s, parseAll=True) res = res[0] print(f'Obtained: {res}') print(f'Expected: {expected}') if expected: assert_equal(res, expected) @comptest def test_parse_language_01(): s = "in:name" e = ExpectInputReceived("name") expect_parse(Syntax.input_received, s, e) expect_parse(Syntax.language, s, e) @comptest def test_parse_language_02(): s = "out:name" e = ExpectOutputProduced("name") expect_parse(Syntax.output_produced, s, e) @comptest def test_parse_language_03(): s = "out:first ; in:second" e = InSequence((ExpectOutputProduced("first"), ExpectInputReceived("second"))) expect_parse(Syntax.language, s, e) @comptest def test_parse_language_04(): s = "(out:first)*" e = ZeroOrMore(ExpectOutputProduced("first")) expect_parse(Syntax.language, s, e) @comptest def test_parse_language_05(): s = "(out:first)?" e = ZeroOrOne(ExpectOutputProduced("first")) expect_parse(Syntax.language, s, e) @comptest def test_parse_language_06(): s = "(out:first)+" e = OneOrMore(ExpectOutputProduced("first")) expect_parse(Syntax.language, s, e) @comptest def test_parse_language_07(): s = "out:first | out:second" e = Either((ExpectOutputProduced("first"), ExpectOutputProduced("second"))) expect_parse(Syntax.language, s, e) s2 = "(out:first | out:second)" expect_parse(Syntax.language, s2, e) @comptest def test_parse_language_08(): s = """ ( in:next_episode ; ( out:no_episodes | (out:episode_start ; (in:next_image ; (out:image | out:episode_end))*) ) )* """ expect_parse(Syntax.language, s, None) # # def test_parse_language_08(): # s = """ # ( # in:next_episode ; ( # out:no_episodes | # (out:episode_start ; # (in:next_image ; (out:image | out:episode_end))*) # ) # )* # """ # # expect_parse(Syntax.language, s, None)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_tests/test_language.py
test_language.py
import os from typing import Sequence, List, Union from networkx.drawing.nx_pydot import write_dot from zuper_nodes import OutputProduced, InputReceived, Event, Language, logger from zuper_nodes.language_parse import parse_language, language_to_str from zuper_nodes.language_recognize import LanguageChecker, Enough, Unexpected, NeedMore from compmake.utils import make_sure_dir_exists from comptests import comptest, run_module_tests, get_comptests_output_dir from zuper_nodes_wrapper.meta_protocol import basic_protocol def assert_seq(s: Union[str, Language], seq: List[Event], expect: Sequence[type], final: type): if isinstance(s, str): s = s.replace('\n', ' ').strip() while ' ' in s: s = s.replace(' ', ' ') l = parse_language(s) else: l = s s2 = language_to_str(l) print(s) print(s2) l2 = parse_language(s2) assert l == l2, (s, s2) pc = LanguageChecker(l) logger.info(f'Active start: {pc.get_active_states_names()}') dn = get_comptests_output_dir() fn = os.path.join(dn, 'language.dot') make_sure_dir_exists(fn) write_dot(pc.g, fn) logger.info(f'Written to {fn}') # all except last for i, (e, r) in enumerate(zip(seq, expect)): logger.info(f'Active before: {pc.get_active_states_names()}') logger.info(f'Event {e}') res = pc.push(e) logger.info(f'Active after: {pc.get_active_states_names()}') if not isinstance(res, r): msg = f'Input {i} ({e}) response was {type(res).__name__} instead of {r.__name__}' msg += f'\n entire sequence: {seq}' msg += f'\n language: {l}' msg += f'\n language string: {s2}' raise Exception(msg) res = pc.finish() if not isinstance(res, final): msg = f'finish response was {type(res).__name__} instead of {final.__name__}' msg += f'\n entire sequence: {seq}' msg += f'\n language: {l}' msg += f'\n language string: {s2}' raise Exception(msg) @comptest def test_proto_out1(): seq = [OutputProduced("a")] assert_seq("out:a", seq, (Enough,), Enough) @comptest def test_proto_in1(): seq = [InputReceived("a")] assert_seq("in:a", seq, (Enough,), Enough) @comptest def test_proto3(): seq = [InputReceived("a")] assert_seq("out:a", seq, (Unexpected,), Unexpected) @comptest def test_proto4(): seq = [OutputProduced("a")] assert_seq("in:a", seq, (Unexpected,), Unexpected) @comptest def test_proto05(): seq = [InputReceived("b")] assert_seq("in:a", seq, (Unexpected,), Unexpected) @comptest def test_proto06(): seq = [OutputProduced("b")] assert_seq("in:a", seq, (Unexpected,), Unexpected) @comptest def test_proto07(): seq = [OutputProduced("a"), OutputProduced("b")] assert_seq("out:a ; out:b", seq, (NeedMore, Enough), Enough) @comptest def test_proto08(): seq = [OutputProduced("a"), OutputProduced("b")] assert_seq("out:a ; out:b ; out:b", seq, (NeedMore, NeedMore), NeedMore) @comptest def test_proto09(): seq = [OutputProduced("a")] assert_seq("out:a ; out:b", seq, (NeedMore,), NeedMore) @comptest def test_proto10(): seq = [OutputProduced("a"), OutputProduced("b"), OutputProduced("c")] assert_seq("out:a ; out:b", seq, (NeedMore, Enough, Unexpected), Unexpected) @comptest def test_proto_zom_01(): seq = [] assert_seq("out:a *", seq, (), Enough) @comptest def test_proto_zom_02(): seq = [OutputProduced("a")] assert_seq("out:a *", seq, (Enough,), Enough) @comptest def test_proto_zom_03(): seq = [OutputProduced("a"), OutputProduced("a")] assert_seq("out:a *", seq, (Enough, Enough), Enough) @comptest def test_proto_either_01(): seq = [OutputProduced("a")] assert_seq("out:a | out:b ", seq, (Enough,), Enough) @comptest def test_proto_either_02(): seq = [OutputProduced("b")] assert_seq("out:a | out:b ", seq, (Enough,), Enough) @comptest def test_proto_either_03(): seq = [OutputProduced("c")] assert_seq("out:a | out:b | out:c ", seq, (Enough,), Enough) @comptest def test_proto_either_04(): seq = [OutputProduced("a"), OutputProduced("b")] assert_seq("(out:a ; out:b) | (out:b ; out:a) ", seq, (NeedMore, Enough), Enough) @comptest def test_proto_either_05(): seq = [OutputProduced("b"), OutputProduced("a")] assert_seq("(out:a ; out:b) | (out:b ; out:a) ", seq, (NeedMore, Enough,), Enough) @comptest def test_proto_oom_01(): seq = [] assert_seq("out:a +", seq, (), NeedMore) @comptest def test_proto_oom_02(): seq = [OutputProduced("a")] assert_seq("out:a +", seq, (Enough,), Enough) @comptest def test_proto_oom_03(): seq = [OutputProduced("a"), OutputProduced("a")] assert_seq("out:a +", seq, (Enough, Enough), Enough) @comptest def test_proto_zoom_01(): seq = [] assert_seq("out:a ?", seq, (), Enough) @comptest def test_proto_zoom_02(): seq = [OutputProduced("a")] assert_seq("out:a ?", seq, (Enough,), Enough) @comptest def test_proto_zoom_03(): seq = [OutputProduced("a"), OutputProduced("a")] assert_seq("out:a ?", seq, (Enough, Unexpected), Unexpected) @comptest def test_protocol_complex1(): l = """ ( in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) )* """ seq = [InputReceived("next_episode"), OutputProduced("episode_start")] assert_seq(l, seq, (NeedMore, Enough), Enough) @comptest def test_protocol_complex1_0(): l = """ in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) """ seq = [InputReceived("next_episode"), OutputProduced("no_more_episodes")] assert_seq(l, seq, (NeedMore, Enough), Enough) @comptest def test_protocol_complex1_1(): l = """ in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) """ seq = [InputReceived("next_episode"), OutputProduced("episode_start")] assert_seq(l, seq, (NeedMore, Enough), Enough) @comptest def test_protocol_complex1_2(): l = """ in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) """ seq = [InputReceived("next_episode"), OutputProduced("episode_start"), InputReceived("next_image"), OutputProduced("image"), ] assert_seq(l, seq, (NeedMore, Enough), Enough) @comptest def test_protocol_complex1_3(): l = """ ( in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) )* """ seq = [ InputReceived("next_image"), ] assert_seq(l, seq, (Unexpected,), Unexpected) @comptest def test_protocol_complex1_3b(): l = """ ( in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) )* """ seq = [ InputReceived("next_image"), ] assert_seq(l, seq, (Unexpected,), Unexpected) @comptest def test_protocol_complex1_3c(): l = """ ( in:next_episode ; ( (out:episode_start ; (in:next_image)*) ) )* """ seq = [ InputReceived("next_image"), ] assert_seq(l, seq, (Unexpected,), Unexpected) @comptest def test_protocol_complex1_3e(): l = """ ( in:next_episode ; ( (out:episode_start ; (in:next_image)*) ) ) """ seq = [ InputReceived("next_image"), ] assert_seq(l, seq, (Unexpected,), Unexpected) @comptest def test_protocol_complex1_3d(): l = """ ( in:next_episode ; ( (out:episode_start ; (in:next_image)) ) )* """ seq = [ InputReceived("next_image"), ] assert_seq(l, seq, (Unexpected,), Unexpected) @comptest def test_protocol_complex1_3v(): l0 = """ out:episode_start ; (in:next_image ; (out:image | out:no_more_images))* """ seq = [OutputProduced("episode_start")] assert_seq(l0, seq, (Enough,), Enough) @comptest def test_basic_protocol1(): l0 = basic_protocol.language seq = [InputReceived("set_config")] assert_seq(l0, seq, (NeedMore,), NeedMore) if __name__ == '__main__': run_module_tests()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_tests/test_protocol.py
test_protocol.py
def test1(): # takes a protocol class MyWrapper:
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_tests/test_meta.py
test_meta.py
from . import test1 from . import test_protocol from . import test_language
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_tests/__init__.py
__init__.py
# coding=utf-8 import termcolor __all__ = ['setup_logging_color', 'setup_logging_format', 'setup_logging', 'logger'] def get_FORMAT_datefmt(): def dark(s): return termcolor.colored(s, attrs=['dark']) pre = dark('%(asctime)s|') pre += '%(name)s' pre += dark('|%(filename)s:%(lineno)s|%(funcName)s(): ') FORMAT = pre + "%(message)s" datefmt = "%H:%M:%S" return FORMAT, datefmt def setup_logging_format(): from logging import Logger, StreamHandler, Formatter import logging FORMAT, datefmt = get_FORMAT_datefmt() logging.basicConfig(format=FORMAT, datefmt=datefmt) if Logger.root.handlers: # @UndefinedVariable for handler in Logger.root.handlers: # @UndefinedVariable if isinstance(handler, StreamHandler): formatter = Formatter(FORMAT, datefmt=datefmt) handler.setFormatter(formatter) else: logging.basicConfig(format=FORMAT, datefmt=datefmt) def add_coloring_to_emit_ansi(fn): # add methods we need to the class def new(*args): levelno = args[1].levelno if levelno >= 50: color = '\x1b[31m' # red elif levelno >= 40: color = '\x1b[31m' # red elif levelno >= 30: color = '\x1b[33m' # yellow elif levelno >= 20: color = '\x1b[32m' # green elif levelno >= 10: color = '\x1b[35m' # pink else: color = '\x1b[0m' # normal msg = str(args[1].msg) lines = msg.split('\n') def color_line(l): return "%s%s%s" % (color, l, '\x1b[0m') # normal lines = list(map(color_line, lines)) args[1].msg = "\n".join(lines) return fn(*args) return new def setup_logging_color(): import platform if platform.system() != 'Windows': emit2 = add_coloring_to_emit_ansi(logging.StreamHandler.emit) logging.StreamHandler.emit = emit2 def setup_logging(): # logging.basicConfig() setup_logging_color() setup_logging_format() import logging logging.basicConfig() setup_logging()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/col_logging.py
col_logging.py
from pyparsing import Suppress, Literal, Keyword, ParserElement, pyparsing_common, opAssoc, operatorPrecedence from .language import ExpectInputReceived, ExpectOutputProduced, InSequence, ZeroOrMore, ZeroOrOne, Either, Language, \ OneOrMore __all__ = [ 'parse_language', 'language_to_str', 'Syntax', ] ParserElement.enablePackrat() S = Suppress L = Literal K = Keyword def parse_language(s: str) -> Language: res = Syntax.language.parseString(s, parseAll=True) res = res[0] return res def language_to_str(l: Language): def quote_if(s): if ';' in s or '|' in s: return "(" + s + ')' else: return s if isinstance(l, ExpectInputReceived): return f"in:{l.channel}" if isinstance(l, ExpectOutputProduced): return f"out:{l.channel}" if isinstance(l, InSequence): return " ; ".join(quote_if(language_to_str(_)) for _ in l.ls) if isinstance(l, Either): return " | ".join(quote_if(language_to_str(_)) for _ in l.ls) if isinstance(l, ZeroOrMore): return "(" + language_to_str(l.l) + ")" + '*' if isinstance(l, OneOrMore): return "(" + language_to_str(l.l) + ")" + '+' if isinstance(l, ZeroOrOne): return "(" + language_to_str(l.l) + ")" + '?' raise NotImplementedError(type(l)) def on_input_received(s, loc, tokens): return ExpectInputReceived(tokens[0]) def on_output_produced(s, loc, tokens): return ExpectOutputProduced(tokens[0]) def on_in_sequence(tokens): return InSequence(tuple(tokens[0])) def on_either(tokens): return Either(tuple(tokens[0])) def on_zero_or_one(tokens): return ZeroOrOne(tokens[0][0]) def on_zero_or_more(tokens): return ZeroOrMore(tokens[0][0]) def on_one_or_more(tokens): return OneOrMore(tokens[0][0]) class Syntax: input_received = S(K("in") + L(":")) + pyparsing_common.identifier output_produced = S(K("out") + L(":")) + pyparsing_common.identifier basic = input_received | output_produced language = operatorPrecedence(basic, [ (S(L('*')), 1, opAssoc.LEFT, on_zero_or_more), (S(L('+')), 1, opAssoc.LEFT, on_one_or_more), (S(L('?')), 1, opAssoc.LEFT, on_zero_or_one), (S(L(';')), 2, opAssoc.LEFT, on_in_sequence), (S(L('|')), 2, opAssoc.LEFT, on_either), ]) input_received.setParseAction(on_input_received) output_produced.setParseAction(on_output_produced)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/language_parse.py
language_parse.py
from contracts import indent from zuper_json.subcheck import can_be_used_as from zuper_nodes import InteractionProtocol class IncompatibleProtocol(Exception): pass def check_compatible_protocol(p1: InteractionProtocol, p2: InteractionProtocol): """ Checks that p1 is a subprotocol of p2 """ try: # check input compatibility # we should have all inputs for k, v2 in p2.inputs.items(): if not k in p1.inputs: msg = f'First protocol misses input "{k}".' raise IncompatibleProtocol(msg) v1 = p1.inputs[k] can, why = can_be_used_as(v1, v2) if not can: msg = f'For input "{k}", cannot use type {v1} as {v2}: {why}' raise IncompatibleProtocol(msg) # check output compatibility # we should have all inputs for k, v2 in p2.outputs.items(): if not k in p1.outputs: msg = f'First protocol misses output "{k}".' raise IncompatibleProtocol(msg) v1 = p1.outputs[k] can, why = can_be_used_as(v1, v2) if not can: msg = f'For output "{k}", cannot use type {v1} as {v2}: {why}' raise IncompatibleProtocol(msg) # XXX: to finish except IncompatibleProtocol as e: msg = 'Cannot say that p1 is a sub-protocol of p2' msg += '\n' + indent(p1, '|', 'p1: |') msg += '\n' + indent(p2, '|', 'p2: |') raise IncompatibleProtocol(msg) from e
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/compatibility.py
compatibility.py
from dataclasses import dataclass from typing import Union, Tuple, Optional, Set from .language import Language, OutputProduced, InputReceived, Event, ExpectInputReceived, ExpectOutputProduced, \ InSequence, ZeroOrMore, Either, OneOrMore, ZeroOrOne from contracts.utils import indent class Result: pass @dataclass class Enough(Result): pass @dataclass class Unexpected(Result): msg: str def __repr__(self): return 'Unexpected:' + indent(self.msg, ' ') @dataclass class NeedMore(Result): pass import networkx as nx NodeName = Tuple[str, ...] class Always: pass def get_nfa(g: Optional[nx.DiGraph], start_node: NodeName, accept_node: NodeName, l: Language, prefix: Tuple[str, ...] = ()): # assert start_node != accept_node if not start_node in g: g.add_node(start_node, label="/".join(start_node)) if not accept_node in g: g.add_node(accept_node, label="/".join(accept_node)) if isinstance(l, ExpectOutputProduced): g.add_edge(start_node, accept_node, event_match=l, label=f'out/{l.channel}') elif isinstance(l, ExpectInputReceived): g.add_edge(start_node, accept_node, event_match=l, label=f'in/{l.channel}') elif isinstance(l, InSequence): current = start_node for i, li in enumerate(l.ls): # if i == len(l.ls) - 1: # n = accept_node # else: n = prefix + (f'after{i}',) g.add_node(n) # logger.debug(f'sequence {i} start {current} to {n}') get_nfa(g, start_node=current, accept_node=n, prefix=prefix + (f'{i}',), l=li) current = n g.add_edge(current, accept_node, event_match=Always(), label='always') elif isinstance(l, ZeroOrMore): # logger.debug(f'zeroormore {start_node} -> {accept_node}') g.add_edge(start_node, accept_node, event_match=Always(), label='always') get_nfa(g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ('zero_or_more',)) elif isinstance(l, OneOrMore): # start to accept get_nfa(g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ('one_or_more', '1')) # accept to accept get_nfa(g, start_node=accept_node, accept_node=accept_node, l=l.l, prefix=prefix + ('one_or_more', '2')) elif isinstance(l, ZeroOrOne): g.add_edge(start_node, accept_node, event_match=Always(), label='always') get_nfa(g, start_node=start_node, accept_node=accept_node, l=l.l, prefix=prefix + ('zero_or_one',)) elif isinstance(l, Either): for i, li in enumerate(l.ls): get_nfa(g, start_node=start_node, accept_node=accept_node, l=li, prefix=prefix + (f'either{i}',)) else: assert False, type(l) def event_matches(l: Language, event: Event): if isinstance(l, ExpectInputReceived): return isinstance(event, InputReceived) and event.channel == l.channel if isinstance(l, ExpectOutputProduced): return isinstance(event, OutputProduced) and event.channel == l.channel if isinstance(l, Always): return False raise NotImplementedError(l) START = ('start',) ACCEPT = ('accept',) class LanguageChecker: g: nx.DiGraph active: Set[NodeName] def __init__(self, language: Language): self.g = nx.MultiDiGraph() self.start_node = START self.accept_node = ACCEPT get_nfa(g=self.g, l=language, start_node=self.start_node, accept_node=self.accept_node, prefix=()) # for (a, b, data) in self.g.out_edges(data=True): # print(f'{a} -> {b} {data["event_match"]}') a = 2 for n in self.g: if n not in [START, ACCEPT]: # noinspection PyUnresolvedReferences self.g.node[n]['label'] = f'S{a}' a += 1 elif n == START: # noinspection PyUnresolvedReferences self.g.node[n]['label'] = 'start' elif n == ACCEPT: # noinspection PyUnresolvedReferences self.g.node[n]['label'] = 'accept' self.active = {self.start_node} # logger.debug(f'active {self.active}') self._evolve_empty() def _evolve_empty(self): while True: now_active = set() for node in self.active: nalways = 0 nother = 0 for (_, neighbor, data) in self.g.out_edges([node], data=True): # print(f'-> {neighbor} {data["event_match"]}') if isinstance(data['event_match'], Always): now_active.add(neighbor) nalways += 1 else: nother += 1 if nother or (nalways == 0): now_active.add(node) if self.active == now_active: break self.active = now_active def push(self, event) -> Result: now_active = set() # print(f'push: active is {self.active}') # print(f'push: considering {event}') for node in self.active: for (_, neighbor, data) in self.g.out_edges([node], data=True): if event_matches(data['event_match'], event): # print(f'now activating {neighbor}') now_active.add(neighbor) # else: # print(f"event_match {event} does not match {data['event_match']}") # # if not now_active: # return Unexpected('') self.active = now_active # print(f'push: now active is {self.active}') self._evolve_empty() # print(f'push: now active is {self.active}') return self.finish() def finish(self) -> Union[NeedMore, Enough, Unexpected]: # print(f'finish: active is {self.active}') if not self.active: return Unexpected('no active') if self.accept_node in self.active: return Enough() return NeedMore() def get_active_states_names(self): return [self.g.nodes[_]['label'] for _ in self.active] def get_expected_events(self) -> Set: events = set() for state in self.active: for (_, neighbor, data) in self.g.out_edges([state], data=True): em = data['event_match'] if not isinstance(em, Always): events.add(em) return events
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/language_recognize.py
language_recognize.py
import socket import time from dataclasses import dataclass, field from typing import Optional, Dict import numpy as np __all__ = [ 'AIDONodesException', 'ProtocolViolation', 'ExternalProtocolViolation', 'InternalProtocolViolation', 'DecodingError', 'EncodingError', 'Timestamp', 'timestamp_from_seconds', 'TimeSpec', 'local_time', 'TimingInfo', 'EnvironmentError', 'NotConforming', 'ExternalTimeout', ] class AIDONodesException(Exception): pass class ProtocolViolation(AIDONodesException): pass class ExternalProtocolViolation(ProtocolViolation): pass class ExternalNodeDidNotUnderstand(ProtocolViolation): pass class RemoteNodeAborted(Exception): pass class ExternalTimeout(ExternalProtocolViolation): pass class InternalProblem(Exception): pass class InternalProtocolViolation(ProtocolViolation): pass class DecodingError(AIDONodesException): pass class EncodingError(AIDONodesException): pass class NotConforming(AIDONodesException): """ The node is not conforming to the protocol. """ pass class EnvironmentError(AIDONodesException): """ Things such as files not existing. """ pass @dataclass class Timestamp: s: int us: int def timestamp_from_seconds(f: float) -> Timestamp: s = int(np.floor(f)) extra = f - s us = int(extra * 1000 * 1000 * 1000) return Timestamp(s, us) @dataclass class TimeSpec: time: Timestamp frame: str clock: str time2: Optional[Timestamp] = None def local_time() -> TimeSpec: s = time.time() hostname = socket.gethostname() return TimeSpec(time=timestamp_from_seconds(s), frame='epoch', clock=hostname) @dataclass class TimingInfo: acquired: Optional[Dict[str, TimeSpec]] = field(default_factory=dict) processed: Optional[Dict[str, TimeSpec]] = field(default_factory=dict) received: Optional[TimeSpec] = None
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/structures.py
structures.py
__version__ = '2.0.3' from .col_logging import logging logger = logging.getLogger('zn') logger.setLevel(logging.DEBUG) logger.info(f'zn {__version__}') from .language import * from .language_parse import * from .language_recognize import * from .structures import *
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/__init__.py
__init__.py
from abc import abstractmethod, ABCMeta from dataclasses import dataclass from typing import Tuple, Dict, Iterator, Optional, Union # Events ChannelName = str class Event: pass @dataclass(frozen=True, unsafe_hash=True) class InputReceived(Event): channel: ChannelName @dataclass(frozen=True, unsafe_hash=True) class OutputProduced(Event): channel: ChannelName # Language over events class Language(metaclass=ABCMeta): @abstractmethod def collect_simple_events(self) -> Iterator[Event]: pass @dataclass(frozen=True, unsafe_hash=True) class ExpectInputReceived(Language): channel: ChannelName def collect_simple_events(self): yield InputReceived(self.channel) @dataclass(frozen=True, unsafe_hash=True) class ExpectOutputProduced(Language): channel: ChannelName def collect_simple_events(self): yield OutputProduced(self.channel) @dataclass(frozen=True, unsafe_hash=True) class InSequence(Language): ls: Tuple[Language, ...] def collect_simple_events(self): for l in self.ls: yield from l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class ZeroOrOne(Language): l: Language def collect_simple_events(self): yield from self.l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class ZeroOrMore(Language): l: Language def collect_simple_events(self): yield from self.l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class OneOrMore(Language): l: Language def collect_simple_events(self): yield from self.l.collect_simple_events() @dataclass(frozen=True, unsafe_hash=True) class Either(Language): ls: Tuple[Language, ...] def collect_simple_events(self): for l in self.ls: yield from l.collect_simple_events() # Interaction protocol @dataclass class InteractionProtocol: # Description description: str # Type for each input or output inputs: Dict[ChannelName, type] outputs: Dict[ChannelName, type] # The interaction language language: str # interaction: Language = None def __post_init__(self): from .language_parse import parse_language, language_to_str self.interaction = parse_language(self.language) simple_events = list(self.interaction.collect_simple_events()) for e in simple_events: if isinstance(e, InputReceived): if e.channel not in self.inputs: msg = f'Could not find input channel "{e.channel}" among {sorted(self.inputs)}.' raise ValueError(msg) if isinstance(e, OutputProduced): if e.channel not in self.outputs: msg = f'Could not find output channel "{e.channel}" among {sorted(self.outputs)}.' raise ValueError(msg) self.language = language_to_str(self.interaction) def particularize(ip: InteractionProtocol, description: Optional[str] = None, inputs: Optional[Dict[str, type]] = None, outputs: Optional[Dict[str, type]] = None) -> InteractionProtocol: inputs2 = dict(ip.inputs) inputs2.update(inputs or {}) outputs2 = dict(ip.outputs) outputs2.update(outputs or {}) language = ip.language description = description or ip.description protocol2 = InteractionProtocol(description, inputs2, outputs2, language) from .compatibility import check_compatible_protocol check_compatible_protocol(protocol2, ip) return protocol2
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes/language.py
language.py
ENV_NAME = 'AIDONODE_NAME' ENV_DATA_IN = 'AIDONODE_DATA_IN' ENV_DATA_OUT = 'AIDONODE_DATA_OUT' ENV_META_IN = 'AIDONODE_META_IN' ENV_META_OUT = 'AIDONODE_META_OUT' ENV_TRANSLATE = 'AIDONODE_TRANSLATE' ENV_ENCODING = 'AIDONODE_ENCODING' ENV_CONFIG = 'AIDONODE_CONFIG' # ENV_ENCODING_JSON = 'json' # ENV_ENCODING_CBOR = 'cbor' # ENV_ENCODING_VALID = [ENV_ENCODING_JSON, ENV_ENCODING_CBOR] KNOWN = [ENV_DATA_IN, ENV_DATA_OUT, ENV_CONFIG, ENV_META_IN, ENV_META_OUT, ENV_NAME, ENV_TRANSLATE, ENV_ENCODING] ATT_CONFIG = 'config' TOPIC_ABORTED = 'aborted' FIELD_COMPAT = 'compat' CUR_PROTOCOL = 'z2' FIELD_DATA = 'data' FIELD_TOPIC = 'topic' FIELD_TIMING = 'timing' FIELD_CONTROL = 'control' CTRL_CAPABILITIES = 'capabilities' CTRL_UNDERSTOOD = 'understood' CTRL_NOT_UNDERSTOOD = 'not-understood' CTRL_OVER = 'over' CTRL_ABORTED = 'aborted' CAPABILITY_PROTOCOL_REFLECTION = 'protocol-reflection'
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/constants.py
constants.py
import argparse import json import os import socket import time import traceback from dataclasses import dataclass from typing import * import yaml from contracts.utils import format_obs from zuper_commons.text import indent from zuper_commons.types import check_isinstance from zuper_json.ipce import object_to_ipce, ipce_to_object from zuper_nodes import InteractionProtocol, InputReceived, OutputProduced, Unexpected, LanguageChecker from zuper_nodes.structures import TimingInfo, local_time, TimeSpec, timestamp_from_seconds, DecodingError, \ ExternalProtocolViolation, NotConforming, ExternalTimeout, InternalProblem from .reading import inputs from .streams import open_for_read, open_for_write from .struct import RawTopicMessage, ControlMessage from .utils import call_if_fun_exists from .writing import Sink from . import logger, logger_interaction from .interface import Context from .meta_protocol import basic_protocol, SetConfig, ProtocolDescription, ConfigDescription, \ BuildDescription, NodeDescription class ConcreteContext(Context): protocol: InteractionProtocol to_write: List[RawTopicMessage] def __init__(self, sink: Sink, protocol: InteractionProtocol, node_name: str, tout: Dict[str, str]): self.sink = sink self.protocol = protocol self.pc = LanguageChecker(protocol.interaction) self.node_name = node_name self.hostname = socket.gethostname() self.tout = tout self.to_write = [] self.last_timing = None def set_last_timing(self, timing: TimingInfo): self.last_timing = timing def get_hostname(self): return self.hostname def write(self, topic, data, timing=None, with_schema=False): if topic not in self.protocol.outputs: msg = f'Output channel "{topic}" not found in protocol; know {sorted(self.protocol.outputs)}.' raise Exception(msg) # logger.info(f'Writing output "{topic}".') klass = self.protocol.outputs[topic] if isinstance(klass, type): check_isinstance(data, klass) event = OutputProduced(topic) res = self.pc.push(event) if isinstance(res, Unexpected): msg = f'Unexpected output {topic}: {res}' logger.error(msg) return klass = self.protocol.outputs[topic] if isinstance(data, dict): data = ipce_to_object(data, {}, {}, expect_type=klass) if timing is None: timing = self.last_timing if timing is not None: s = time.time() if timing.received is None: # XXX time1 = timestamp_from_seconds(s) else: time1 = timing.received.time processed = TimeSpec(time=time1, time2=timestamp_from_seconds(s), frame='epoch', clock=socket.gethostname()) timing.processed[self.node_name] = processed timing.received = None topic_o = self.tout.get(topic, topic) data = object_to_ipce(data, {}, with_schema=with_schema) if timing is not None: timing_o = object_to_ipce(timing, {}, with_schema=False) else: timing_o = None rtm = RawTopicMessage(topic_o, data, timing_o) self.to_write.append(rtm) def get_to_write(self) -> List[RawTopicMessage]: """ Returns the messages to send and resets the queue""" res = self.to_write self.to_write = [] return res def log(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.info(prefix + s) def info(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.info(prefix + s) def debug(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.debug(prefix + s) def warning(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.warning(prefix + s) def error(self, s): prefix = f'{self.hostname}:{self.node_name}: ' logger.error(prefix + s) def get_translation_table(t: str) -> Tuple[Dict[str, str], Dict[str, str]]: tout = {} tin = {} for t in t.split(','): ts = t.split(':') if ts[0] == 'in': tin[ts[1]] = ts[2] if ts[0] == 'out': tout[ts[1]] = ts[2] return tin, tout def check_variables(): for k, v in os.environ.items(): if k.startswith('AIDO') and k not in KNOWN: msg = f'I do not expect variable "{k}" set in environment with value "{v}".' msg += ' I expect: %s' % ", ".join(KNOWN) logger.warn(msg) from .constants import * def run_loop(node, protocol: InteractionProtocol, args: Optional[List[str]] = None): parser = argparse.ArgumentParser() check_variables() data_in = os.environ.get(ENV_DATA_IN, '/dev/stdin') data_out = os.environ.get(ENV_DATA_OUT, '/dev/stdout') default_name = os.environ.get(ENV_NAME, None) translate = os.environ.get(ENV_TRANSLATE, '') config = os.environ.get(ENV_CONFIG, '{}') parser.add_argument('--data-in', default=data_in) parser.add_argument('--data-out', default=data_out) parser.add_argument('--name', default=default_name) parser.add_argument('--config', default=config) parser.add_argument('--translate', default=translate) parser.add_argument('--loose', default=False, action='store_true') parsed = parser.parse_args(args) tin, tout = get_translation_table(parsed.translate) # expect in:name1:name2, out:name2:name1 fin = parsed.data_in fout = parsed.data_out fi = open_for_read(fin) fo = open_for_write(fout) node_name = parsed.name or type(node).__name__ logger.name = node_name config = yaml.load(config, Loader=yaml.SafeLoader) try: loop(node_name, fi, fo, node, protocol, tin, tout, config=config) except BaseException as e: msg = f'Error in node {node_name}' logger.error(f'Error in node {node_name}: \n{traceback.format_exc()}') raise Exception(msg) from e finally: fo.flush() fo.close() fi.close() def loop(node_name: str, fi, fo, node, protocol: InteractionProtocol, tin, tout, config: dict): logger.info(f'Starting reading') initialized = False context_data = None sink = Sink(fo) try: context_data = ConcreteContext(sink=sink, protocol=protocol, node_name=node_name, tout=tout) context_meta = ConcreteContext(sink=sink, protocol=basic_protocol, node_name=node_name + '.wrapper', tout=tout) wrapper = MetaHandler(node, protocol) for k, v in config.items(): wrapper.set_config(k, v) waiting_for = 'Expecting control message or one of: %s' % context_data.pc.get_expected_events() for parsed in inputs(fi, waiting_for=waiting_for): if isinstance(parsed, ControlMessage): expect = [CTRL_CAPABILITIES] if parsed.code not in expect: msg = f'I expect any of {expect}, not "{parsed.code}".' sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg) sink.write_control_message(CTRL_OVER) else: if parsed.code == CTRL_CAPABILITIES: my_capabilities = { 'z2': { CAPABILITY_PROTOCOL_REFLECTION: True } } sink.write_control_message(CTRL_UNDERSTOOD) sink.write_control_message(CTRL_CAPABILITIES, my_capabilities) sink.write_control_message(CTRL_OVER) else: assert False elif isinstance(parsed, RawTopicMessage): parsed.topic = tin.get(parsed.topic, parsed.topic) logger_interaction.info(f'Received message of topic "{parsed.topic}".') if parsed.topic.startswith('wrapper.'): parsed.topic = parsed.topic.replace('wrapper.', '') receiver0 = wrapper context0 = context_meta else: receiver0 = node context0 = context_data if receiver0 is node and not initialized: try: call_if_fun_exists(node, 'init', context=context_data) except BaseException as e: msg = "Exception while calling the node's init() function." msg += '\n\n' + indent(traceback.format_exc(), '| ') context_meta.write('aborted', msg) raise Exception(msg) from e initialized = True if parsed.topic not in context0.protocol.inputs: msg = f'Input channel "{parsed.topic}" not found in protocol. ' msg += f'\n\nKnown channels: {sorted(context0.protocol.inputs)}' sink.write_control_message(CTRL_NOT_UNDERSTOOD, msg) sink.write_control_message(CTRL_OVER) raise ExternalProtocolViolation(msg) sink.write_control_message(CTRL_UNDERSTOOD) try: handle_message_node(parsed, receiver0, context0) to_write = context0.get_to_write() # msg = f'I wrote {len(to_write)} messages.' # logger.info(msg) for rtm in to_write: sink.write_topic_message(rtm.topic, rtm.data, rtm.timing) sink.write_control_message(CTRL_OVER) except BaseException as e: msg = f'Exception while handling a message on topic "{parsed.topic}".' msg += '\n\n' + indent(traceback.format_exc(), '| ') sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise InternalProblem(msg) from e # XXX else: assert False res = context_data.pc.finish() if isinstance(res, Unexpected): msg = f'Protocol did not finish: {res}' logger_interaction.error(msg) if initialized: try: call_if_fun_exists(node, 'finish', context=context_data) except BaseException as e: msg = "Exception while calling the node's finish() function." msg += '\n\n' + indent(traceback.format_exc(), '| ') context_meta.write('aborted', msg) raise Exception(msg) from e except BrokenPipeError: msg = 'The other side closed communication.' logger.info(msg) return except ExternalTimeout as e: msg = 'Could not receive any other messages.' if context_data: msg += '\n Expecting one of: %s' % context_data.pc.get_expected_events() sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise ExternalTimeout(msg) from e except InternalProblem: raise except BaseException as e: msg = f"Unexpected error:" msg += '\n\n' + indent(traceback.format_exc(), '| ') sink.write_control_message(CTRL_ABORTED, msg) sink.write_control_message(CTRL_OVER) raise InternalProblem(msg) from e # XXX class MetaHandler: def __init__(self, node, protocol): self.node = node self.protocol = protocol def set_config(self, key, value): if hasattr(self.node, ATT_CONFIG): config = self.node.config if hasattr(config, key): setattr(self.node.config, key, value) else: msg = f'Could not find config key {key}' raise ValueError(msg) else: msg = 'Node does not have the "config" attribute.' raise ValueError(msg) def on_received_set_config(self, context, data: SetConfig): key = data.key value = data.value try: self.set_config(key, value) except ValueError as e: context.write('set_config_error', str(e)) else: context.write('set_config_ack', None) def on_received_describe_protocol(self, context): desc = ProtocolDescription(data=self.protocol, meta=basic_protocol) context.write('protocol_description', desc) def on_received_describe_config(self, context): K = type(self.node) if hasattr(K, '__annotations__') and ATT_CONFIG in K.__annotations__: config_type = K.__annotations__[ATT_CONFIG] config_current = getattr(self.node, ATT_CONFIG) else: @dataclass class NoConfig: pass config_type = NoConfig config_current = NoConfig() desc = ConfigDescription(config=config_type, current=config_current) context.write('config_description', desc, with_schema=True) def on_received_describe_node(self, context): desc = NodeDescription(self.node.__doc__) context.write('node_description', desc, with_schema=True) def on_received_describe_build(self, context): desc = BuildDescription() context.write('build_description', desc, with_schema=True) def handle_message_node(parsed: RawTopicMessage, agent, context: ConcreteContext): protocol = context.protocol topic = parsed.topic data = parsed.data pc = context.pc klass = protocol.inputs[topic] try: ob = ipce_to_object(data, {}, {}, expect_type=klass) except BaseException as e: msg = f'Cannot deserialize object for topic "{topic}" expecting {klass}.' try: parsed = json.dumps(parsed, indent=2) except: parsed = str(parsed) msg += '\n\n' + indent(parsed, '|', 'parsed: |') raise DecodingError(msg) from e if parsed.timing is not None: timing = ipce_to_object(parsed.timing, {}, {}, expect_type=TimingInfo) else: timing = TimingInfo() timing.received = local_time() context.set_last_timing(timing) # logger.info(f'Before push the state is\n{pc}') event = InputReceived(topic) expected = pc.get_expected_events() res = pc.push(event) # names = pc.get_active_states_names() # logger.info(f'After push of {event}: result \n{res} active {names}' ) if isinstance(res, Unexpected): msg = f'Unexpected input "{topic}": {res}' msg += f'\nI expected: {expected}' msg += '\n' + format_obs(dict(pc=pc)) logger.error(msg) raise ExternalProtocolViolation(msg) else: expect_fn = f'on_received_{topic}' call_if_fun_exists(agent, expect_fn, data=ob, context=context, timing=timing) def check_implementation(node, protocol: InteractionProtocol): logger.info('checking implementation') for n in protocol.inputs: expect_fn = f'on_received_{n}' if not hasattr(node, expect_fn): msg = f'Missing function {expect_fn}' msg += f'\nI know {sorted(type(node).__dict__)}' raise NotConforming(msg) for x in type(node).__dict__: if x.startswith('on_received_'): input_name = x.replace('on_received_', '') if input_name not in protocol.inputs: msg = f'The node has function "{x}" but there is no input "{input_name}".' raise NotConforming(msg)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/wrapper.py
wrapper.py
import os import stat import time from io import BufferedReader from zuper_commons.fs import make_sure_dir_exists from . import logger_interaction from . import logger def wait_for_creation(fn): while not os.path.exists(fn): msg = 'waiting for creation of %s' % fn logger.info(msg) time.sleep(1) def open_for_read(fin, timeout=None): t0 = time.time() # first open reader file in case somebody is waiting for it while not os.path.exists(fin): delta = time.time() - t0 if timeout is not None and (delta > timeout): msg = f'The file {fin} was not created before {timeout} seconds. I give up.' raise EnvironmentError(msg) logger_interaction.info(f'waiting for file {fin} to be created') time.sleep(1) logger_interaction.info(f'Opening input {fin}') fi = open(fin, 'rb', buffering=0) # noinspection PyTypeChecker fi = BufferedReader(fi, buffer_size=1) return fi def open_for_write(fout): if fout == '/dev/stdout': return open('/dev/stdout', 'wb', buffering=0) else: wants_fifo = fout.startswith('fifo:') fout = fout.replace('fifo:', '') logger_interaction.info(f'Opening output file {fout} (wants fifo: {wants_fifo})') if not os.path.exists(fout): if wants_fifo: make_sure_dir_exists(fout) os.mkfifo(fout) logger_interaction.info('Fifo created.') else: is_fifo = stat.S_ISFIFO(os.stat(fout).st_mode) if wants_fifo and not is_fifo: logger_interaction.info(f'Recreating {fout} as a fifo.') os.unlink(fout) os.mkfifo(fout) if wants_fifo: logger_interaction.info('Fifo detected. Opening will block until a reader appears.') make_sure_dir_exists(fout) fo = open(fout, 'wb', buffering=0) if wants_fifo: logger_interaction.info('Reader has connected to my fifo') return fo
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/streams.py
streams.py
import cbor2 from . import logger from .constants import * class Sink: def __init__(self, of): self.of = of def write_topic_message(self, topic, data, timing): """ Can raise BrokenPipeError""" m = {} m[FIELD_COMPAT] = [CUR_PROTOCOL] m[FIELD_TOPIC] = topic m[FIELD_DATA] = data m[FIELD_TIMING] = timing self._write_raw(m) def write_control_message(self, code, data=None): """ Can raise BrokenPipeError""" m = {} m[FIELD_CONTROL] = code m[FIELD_DATA] = data self._write_raw(m) def _write_raw(self, m: dict): """ Can raise BrokenPipeError""" j = cbor2.dumps(m) self.of.write(j) self.of.flush()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/writing.py
writing.py
from dataclasses import dataclass from typing import * from .constants import * from zuper_nodes.structures import TimingInfo X = TypeVar('X') @dataclass class MsgReceived(Generic[X]): topic: str data: X timing: TimingInfo @dataclass class RawTopicMessage: topic: str data: Optional[dict] timing: Optional[dict] @dataclass class ControlMessage: code: str msg: Optional[str] WireMessage = NewType('WireMessage', dict) class Malformed(Exception): pass def interpret_control_message(m: WireMessage) -> ControlMessage: if not isinstance(m, dict): msg = f'Expected dictionary, not {type(m)}.' raise Malformed(msg) if not FIELD_CONTROL in m: msg = f'Expected field {FIELD_CONTROL}, obtained {list(m)}.' raise Malformed(msg) code = m[FIELD_CONTROL] msg = m.get(FIELD_DATA, None) return ControlMessage(code, msg)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/struct.py
struct.py
import inspect from . import logger def call_if_fun_exists(ob, fname, **kwargs): kwargs = dict(kwargs) if not hasattr(ob, fname): msg = f'Missing function {fname}() for {type(ob)}' logger.warning(msg) return f = getattr(ob, fname) a = inspect.getfullargspec(f) for k, v in dict(kwargs).items(): if k not in a.args: kwargs.pop(k) try: f(**kwargs) except TypeError as e: msg = f'Cannot call function {f} with arguments {kwargs}.' msg += f'\n\nargspec: {a}' raise TypeError(msg) from e
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/utils.py
utils.py
from dataclasses import dataclass from typing import * from zuper_nodes import InteractionProtocol @dataclass class SetConfig: key: str value: Any @dataclass class ConfigDescription: config: type current: Any @dataclass class NodeDescription: description: str @dataclass class BuildDescription: pass @dataclass class ProtocolDescription: data: InteractionProtocol meta: InteractionProtocol @dataclass class CommsHealth: # ignored because not compatible ignored: Dict[str, int] # unexpected topics unexpected: Dict[str, int] # malformed data malformed: Dict[str, int] # if we are completely lost unrecoverable_protocol_error: bool @dataclass class NodeHealth: # there is a critical error that makes it useless to continue critical: bool # severe problem but we can continue severe: bool # a minor problem to report minor: bool details: str LogEntry = str basic_protocol = InteractionProtocol( description="""\ Basic interaction protocol for nodes spoken by the node wrapper. """, inputs={ "describe_config": type(None), "set_config": SetConfig, "describe_protocol": type(None), "describe_node": type(None), "describe_build": type(None), "get_state": type(None), "set_state": Any, "get_logs": type(None), }, language="""\ ( (in:describe_config ; out:config_description) | (in:set_config ; (out:set_config_ack | out:set_config_error)) | (in:describe_protocol ; out:protocol_description) | (in:describe_node ; out:node_description) | (in:describe_build ; out:build_description) | (in:get_state ; out:node_state) | (in:set_state ; (out:set_state_ack| out:set_state_error) ) | (in:get_logs ; out:logs) | out:aborted )* """, outputs={ "config_description": ConfigDescription, 'set_config_ack': type(None), 'set_config_error': str, 'protocol_description': ProtocolDescription, 'node_description': NodeDescription, 'build_description': BuildDescription, 'node_state': Any, 'set_state_ack': type(None), 'set_state_error': str, 'logs': List[LogEntry], 'aborted': str, })
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/meta_protocol.py
meta_protocol.py
import sys from abc import ABCMeta, abstractmethod from typing import * from zuper_nodes.structures import TimingInfo __all__ = [ 'Context', 'wrap_direct', ] def wrap_direct(node, protocol, args: Optional[List[str]] = None): if args is None: args = sys.argv[1:] from zuper_commons.logs import monkeypatch_findCaller from zuper_nodes_wrapper.wrapper import check_implementation, run_loop monkeypatch_findCaller() check_implementation(node, protocol) run_loop(node, protocol, args) class Context(metaclass=ABCMeta): @abstractmethod def write(self, topic: str, data: Any, timing: TimingInfo = None, with_schema: bool = False): pass @abstractmethod def info(self, msg: str): pass @abstractmethod def debug(self, msg: str): pass @abstractmethod def warning(self, msg: str): pass @abstractmethod def error(self, msg: str): pass @abstractmethod def get_hostname(self): pass
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/interface.py
interface.py
import os from io import BufferedReader from typing import * import cbor2 as cbor from zuper_commons.text import indent from zuper_json.ipce import object_to_ipce, ipce_to_object from zuper_json.json2cbor import read_next_cbor from zuper_nodes import InteractionProtocol, ExternalProtocolViolation from zuper_nodes.compatibility import check_compatible_protocol from zuper_nodes.structures import TimingInfo, RemoteNodeAborted, ExternalNodeDidNotUnderstand from zuper_nodes_wrapper.meta_protocol import ProtocolDescription, basic_protocol from zuper_nodes_wrapper.streams import wait_for_creation from zuper_nodes_wrapper.struct import MsgReceived, interpret_control_message, WireMessage from . import logger, logger_interaction from .constants import * class ComponentInterface: def __init__(self, fnin: str, fnout: str, expect_protocol: InteractionProtocol, nickname: str, timeout=None): self.nickname = nickname self._cc = None try: os.mkfifo(fnin) except BaseException as e: msg = f'Cannot create fifo {fnin}' raise Exception(msg) from e self.fpin = open(fnin, 'wb', buffering=0) wait_for_creation(fnout) self.fnout = fnout f = open(fnout, 'rb', buffering=0) # noinspection PyTypeChecker self.fpout = BufferedReader(f, buffer_size=1) self.nreceived = 0 self.expect_protocol = expect_protocol self.node_protocol = None self.data_protocol = None self.timeout = timeout def close(self): self.fpin.close() self.fpout.close() def cc(self, f): """ CC-s everything that is read or written to this file. """ self._cc = f def _get_node_protocol(self, timeout=None): self.my_capabilities = {'z2': {CAPABILITY_PROTOCOL_REFLECTION: True}} msg = {FIELD_CONTROL: CTRL_CAPABILITIES, FIELD_DATA: self.my_capabilities} j = self._serialize(msg) self._write(j) msgs = read_reply(self.fpout, timeout=timeout, waiting_for=f"Reading {self.nickname} capabilities", nickname=self.nickname) self.node_capabilities = msgs[0]['data'] logger.info('My capabilities: %s' % self.my_capabilities) logger.info('Found capabilities: %s' % self.node_capabilities) if 'z2' not in self.node_capabilities: msg = 'Incompatible node; capabilities %s' % self.node_capabilities raise ExternalProtocolViolation(msg) z = self.node_capabilities['z2'] if not z.get(CAPABILITY_PROTOCOL_REFLECTION, False): logger.info('Node does not support reflection.') if self.expect_protocol is None: msg = 'Node does not support reflection - need to provide protocol.' raise Exception(msg) else: ob: MsgReceived[ProtocolDescription] = \ self.write_topic_and_expect('wrapper.describe_protocol', expect='protocol_description', timeout=timeout) self.node_protocol = ob.data.data self.data_protocol = ob.data.meta if self.expect_protocol is not None: check_compatible_protocol(self.node_protocol, self.expect_protocol) def write_topic_and_expect(self, topic, data=None, with_schema=False, timeout=None, timing=None, expect=None) -> MsgReceived: timeout = timeout or self.timeout self._write_topic(topic, data=data, with_schema=with_schema, timing=timing) ob: MsgReceived = self.read_one(expect_topic=expect, timeout=timeout) return ob def write_topic_and_expect_zero(self, topic, data=None, with_schema=False, timeout=None, timing=None): timeout = timeout or self.timeout self._write_topic(topic, data=data, with_schema=with_schema, timing=timing) msgs = read_reply(self.fpout, timeout=timeout, nickname=self.nickname) if msgs: msg = 'Expecting zero, got %s' % msgs raise ExternalProtocolViolation(msg) def _write_topic(self, topic, data=None, with_schema=False, timing=None): suggest_type = None if self.node_protocol: if topic in self.node_protocol.inputs: suggest_type = self.node_protocol.inputs[topic] ipce = object_to_ipce(data, {}, with_schema=with_schema, suggest_type=suggest_type) # try to re-read if suggest_type: try: _ = ipce_to_object(ipce, {}, expect_type=suggest_type) except BaseException as e: msg = f'While attempting to write on topic "{topic}", cannot ' \ f'interpret the value as {suggest_type}.\nValue: {data}' raise Exception(msg) from e # XXX msg = {FIELD_COMPAT: [CUR_PROTOCOL], FIELD_TOPIC: topic, FIELD_DATA: ipce, FIELD_TIMING: timing} j = self._serialize(msg) self._write(j) # make sure we write the schema when we copy it if not with_schema: msg[FIELD_DATA] = object_to_ipce(data, {}, with_schema=True) j = self._serialize(msg) if self._cc: self._cc.write(j) self._cc.flush() logger_interaction.info(f'Written to topic "{topic}" >> {self.nickname}.') def _write(self, j): try: self.fpin.write(j) self.fpin.flush() except BrokenPipeError as e: msg = f'While attempting to write to node "{self.nickname}", ' \ f'I reckon that the pipe is closed and the node exited.' try: received = self.read_one(expect_topic=TOPIC_ABORTED) if received.topic == TOPIC_ABORTED: msg += '\n\nThis is the aborted message:' msg += '\n\n' + indent(received.data, ' |') except BaseException as e2: msg += f'\n\nI could not read any aborted message: {e2}' raise RemoteNodeAborted(msg) from e def _serialize(self, msg) -> bytes: j = cbor.dumps(msg) return j def read_one(self, expect_topic=None, timeout=None) -> MsgReceived: timeout = timeout or self.timeout try: if expect_topic: waiting_for = f'Expecting topic "{expect_topic}" << {self.nickname}.' else: waiting_for = None msgs = read_reply(self.fpout, timeout=timeout, waiting_for=waiting_for, nickname=self.nickname) if len(msgs) == 0: msg = f'Expected one message from node "{self.nickname}". Got zero.' if expect_topic: msg += f'\nExpecting topic "{expect_topic}".' raise ExternalProtocolViolation(msg) if len(msgs) > 1: msg = f'Expected only one message. Got {msgs}' raise ExternalProtocolViolation(msg) msg = msgs[0] if FIELD_TOPIC not in msg: m = f'Invalid message does not contain the field "{FIELD_TOPIC}".' m += f'\n {msg}' raise ExternalProtocolViolation(m) topic = msg[FIELD_TOPIC] if expect_topic: if topic != expect_topic: msg = f'I expected topic "{expect_topic}" but received "{topic}".' raise ExternalProtocolViolation(msg) if topic in basic_protocol.outputs: klass = basic_protocol.outputs[topic] else: if self.node_protocol: if topic not in self.node_protocol.outputs: msg = f'Cannot find topic "{topic}" in outputs of detected node protocol.' msg += '\nI know: %s' % sorted(self.node_protocol.outputs) raise ExternalProtocolViolation(msg) else: klass = self.node_protocol.outputs[topic] else: if not topic in self.expect_protocol.outputs: msg = f'Cannot find topic "{topic}".' raise ExternalProtocolViolation(msg) else: klass = self.expect_protocol.outputs[topic] data = ipce_to_object(msg[FIELD_DATA], {}, expect_type=klass) if self._cc: msg[FIELD_DATA] = object_to_ipce(data, {}, with_schema=True) msg_b = self._serialize(msg) self._cc.write(msg_b) self._cc.flush() if FIELD_TIMING not in msg: timing = TimingInfo() else: timing = ipce_to_object(msg[FIELD_TIMING], {}, expect_type=TimingInfo) self.nreceived += 1 return MsgReceived[klass](topic, data, timing) except StopIteration as e: msg = 'EOF detected on %s after %d messages.' % (self.fnout, self.nreceived) if expect_topic: msg += f' Expected topic "{expect_topic}".' raise StopIteration(msg) from e except TimeoutError as e: msg = 'Timeout detected on %s after %d messages.' % (self.fnout, self.nreceived) if expect_topic: msg += f' Expected topic "{expect_topic}".' raise TimeoutError(msg) from e def read_reply(fpout, nickname: str, timeout=None, waiting_for=None, ) -> List: """ Reads a control message. Returns if it is CTRL_UNDERSTOOD. Raises: TimeoutError RemoteNodeAborted ExternalNodeDidNotUnderstand ExternalProtocolViolation otherwise. """ try: wm: WireMessage = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for) # logger.debug(f'{nickname} sent {wm}') except StopIteration: msg = 'Remote node closed communication (%s)' % waiting_for raise RemoteNodeAborted(msg) from None cm = interpret_control_message(wm) if cm.code == CTRL_UNDERSTOOD: others = read_until_over(fpout, timeout=timeout, nickname=nickname) return others elif cm.code == CTRL_ABORTED: msg = f'The remote node "{nickname}" aborted with the following error:' msg += '\n\n' + indent(cm.msg, "|", f"error in {nickname} |") # others = self.read_until_over() raise RemoteNodeAborted(msg) elif cm.code == CTRL_NOT_UNDERSTOOD: _others = read_until_over(fpout, timeout=timeout, nickname=nickname) msg = f'The remote node "{nickname}" reports that it did not understand the message:' msg += '\n\n' + indent(cm.msg, "|", f"reported by {nickname} |") raise ExternalNodeDidNotUnderstand(msg) else: msg = 'Remote node raised unknown code %s: %s' % (cm, cm.code) raise ExternalProtocolViolation(msg) def read_until_over(fpout, timeout, nickname) -> List[WireMessage]: """ Raises RemoteNodeAborted, TimeoutError """ res = [] waiting_for = f'Reading reply of {nickname}.' while True: try: wm: WireMessage = read_next_cbor(fpout, timeout=timeout, waiting_for=waiting_for) if wm.get(FIELD_CONTROL, '') == CTRL_ABORTED: m = f'External node "{nickname}" aborted:' m += '\n\n' + indent(wm.get(FIELD_DATA, None), "|", f"error in {nickname} |") raise RemoteNodeAborted(m) if wm.get(FIELD_CONTROL, '') == CTRL_OVER: # logger.info(f'Node "{nickname}" concluded output of %s messages.' % len(res)) break # logger.info(f'Node "{nickname}" sent %s.' % len(wm)) except StopIteration: msg = f'External node "{nickname}" closed communication.' raise RemoteNodeAborted(msg) from None except TimeoutError: msg = f'Timeout while reading output of node "{nickname}".' raise TimeoutError(msg) from None res.append(wm) return res
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/wrapper_outside.py
wrapper_outside.py
import logging logger = logging.getLogger('znw') logger.setLevel(logging.DEBUG) logger_interaction = logger.getChild("interaction") logger_interaction.setLevel(logging.CRITICAL) from .interface import *
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/__init__.py
__init__.py
import select import time from typing import * from zuper_commons.text import indent from zuper_json.json2cbor import read_next_cbor from zuper_nodes.structures import ExternalTimeout from zuper_nodes_wrapper.struct import interpret_control_message, RawTopicMessage, ControlMessage from . import logger from .constants import * M = Union[RawTopicMessage, ControlMessage] def inputs(f, give_up: Optional[float] = None, waiting_for: str = None) -> Iterator[M]: last = time.time() intermediate_timeout = 3.0 intermediate_timeout_multiplier = 1.5 while True: readyr, readyw, readyx = select.select([f], [], [f], intermediate_timeout) if readyr: try: parsed = read_next_cbor(f, waiting_for=waiting_for) except StopIteration: return if not isinstance(parsed, dict): msg = f'Expected a dictionary, obtained {parsed!r}' logger.error(msg) continue if FIELD_CONTROL in parsed: m = interpret_control_message(parsed) yield m elif FIELD_TOPIC in parsed: if not FIELD_COMPAT in parsed: msg = f'Could not find field "compat" in structure "{parsed}".' logger.error(msg) continue l = parsed[FIELD_COMPAT] if not isinstance(l, list): msg = f'Expected a list for compatibility value, found {l!r}' logger.error(msg) continue if not CUR_PROTOCOL in parsed[FIELD_COMPAT]: msg = f'Skipping message because could not find {CUR_PROTOCOL} in {l}.' logger.warn(msg) continue rtm = RawTopicMessage(parsed[FIELD_TOPIC], parsed.get(FIELD_DATA, None), parsed.get(FIELD_TIMING, None)) yield rtm elif readyx: logger.warning('Exceptional condition on input channel %s' % readyx) else: delta = time.time() - last if give_up is not None and (delta > give_up): msg = f'I am giving up after %.1f seconds.' % delta raise ExternalTimeout(msg) else: intermediate_timeout *= intermediate_timeout_multiplier msg = f'Input channel not ready after %.1f seconds. Will re-try.' % delta if waiting_for: msg += '\n' + indent(waiting_for, '> ') msg = 'I will warn again in %.1f seconds.' % intermediate_timeout logger.warning(msg)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/reading.py
reading.py
import argparse import dataclasses import json import subprocess import sys from dataclasses import dataclass from io import BytesIO, BufferedReader import cbor2 import yaml from zuper_nodes import InteractionProtocol from zuper_nodes_wrapper.meta_protocol import BuildDescription, NodeDescription, ConfigDescription, ProtocolDescription from contracts import indent from zuper_json import read_cbor_or_json_objects from zuper_json.ipce import ipce_to_object from . import logger def identify_main(): usage = None parser = argparse.ArgumentParser(usage=usage) parser.add_argument('--image', default=None) parser.add_argument('--command', default=None) parsed = parser.parse_args() image = parsed.image if image is not None: ni: NodeInfo = identify_image2(image) elif parsed.command is not None: command = parsed.command.split() ni: NodeInfo = identify_command(command) else: msg = 'Please specify either --image or --command' logger.error(msg) sys.exit(1) print('\n\n') print(indent(describe_nd(ni.nd), '', 'desc: ')) print('\n\n') print(indent(describe_bd(ni.bd), '', 'build: ')) print('\n\n') print(indent(describe_cd(ni.cd), '', 'config: ')) print('\n\n') print(indent(describe(ni.pd.data), '', 'data: ')) print('\n\n') print(indent(describe(ni.pd.meta), '', 'meta: ')) def describe_nd(nd: NodeDescription): return str(nd.description) def describe_bd(nd: BuildDescription): return str(nd) def describe_cd(nd: ConfigDescription): s = [] for f in dataclasses.fields(nd.config): # for k, v in nd.config.__annotations__.items(): s.append('%20s: %s = %s' % (f.name, f.type, f.default)) if not s: return 'No configuration switches available.' if hasattr(nd.config, '__doc__'): s.insert(0, nd.config.__doc__) return "\n".join(s) def describe(ip: InteractionProtocol): s = "InteractionProtocol" s += '\n\n' + '* Description:' s += '\n\n' + indent(ip.description.strip(), ' ') s += '\n\n' + '* Inputs:' for name, type_ in ip.inputs.items(): s += '\n %25s: %s' % (name, type_) s += '\n\n' + '* Outputs:' for name, type_ in ip.outputs.items(): s += '\n %25s: %s' % (name, type_) s += '\n\n' + '* Language:' s += '\n\n' + ip.language return s @dataclass class NodeInfo: pd: ProtocolDescription nd: NodeDescription bd: BuildDescription cd: ConfigDescription def identify_command(command) -> NodeInfo: d = [{'topic': 'wrapper.describe_protocol'}, {'topic': 'wrapper.describe_config'}, {'topic': 'wrapper.describe_node'}, {'topic': 'wrapper.describe_build'} ] to_send = b'' for p in d: p['compat'] = ['aido2'] # to_send += (json.dumps(p) + '\n').encode('utf-8') to_send += cbor2.dumps(p) cp = subprocess.run(command, input=to_send, capture_output=True) s = cp.stderr.decode('utf-8') sys.stderr.write(indent(s.strip(), '|', ' stderr: |') + '\n\n') # noinspection PyTypeChecker f = BufferedReader(BytesIO(cp.stdout)) stream = read_cbor_or_json_objects(f) res = stream.__next__() logger.debug(yaml.dump(res)) pd: ProtocolDescription = ipce_to_object(res['data'], {}, {}, expect_type=ProtocolDescription) res = stream.__next__() logger.debug(yaml.dump(res)) cd: ConfigDescription = ipce_to_object(res['data'], {}, {}, expect_type=ConfigDescription) res = stream.__next__() logger.debug(yaml.dump(res)) nd: NodeDescription = ipce_to_object(res['data'], {}, {}, expect_type=NodeDescription) res = stream.__next__() logger.debug(yaml.dump(res)) bd: BuildDescription = ipce_to_object(res['data'], {}, {}, expect_type=BuildDescription) logger.debug(yaml.dump(res)) return NodeInfo(pd, nd, bd, cd) def identify_image2(image) -> NodeInfo: cmd = ['docker', 'run', '--rm', '-i', image] return identify_command(cmd) # def identify_image(image): # import docker # client = docker.from_env() # # # container: Container = client.containers.create(image, detach=True, stdin_open=True) # print(container) # # time.sleep(4) # # attach to the container stdin socket # container.start() # # s = container.exec_run() # s: SocketIO = container.attach_socket(params={'stdin': 1, 'stream': 1, 'stderr': 0, 'stdout': 0}) # s_out: SocketIO = container.attach_socket(params={ 'stream': 1, 'stdout': 1, 'stderr': 0, 'stdin': 0}) # s_stderr: SocketIO = container.attach_socket(params={'stream': 1, 'stdout': 0, 'stderr': 1, 'stdin': 0}) # print(s.__dict__) # print(s_out.__dict__) # # send text # # s.write(j) # os.write(s._sock.fileno(), j) # os.close(s._sock.fileno()) # s._sock.close() # # s.close() # # f = os.fdopen(s_out._sock.fileno(), 'rb') # # there is some garbage: b'\x01\x00\x00\x00\x00\x00\x1e|{ # f.read(8) # # for x in read_cbor_or_json_objects(f): # print(x) # print(f.read(10)) # # print(os.read(s_out._sock.fileno(), 100)) # # print(os.read(s_stderr._sock.fileno(), 100)) # # close, stop and disconnect # s.close()
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/src/zuper_nodes_wrapper/identify.py
identify.py
Nodes should be able to specify components simulator_protocol = InteractionProtocol( description="""\ Interface to be implemented by a simulator. ```python language="(in:image ; out:image_out)*" components={ 'sub1': filter1, 'sub2': filter1, } inputs={ } connections=[ '(image) -> |sub1| -> |sub2| -> (image_out)' ] ``` def on_image_received(self, context, data): context.send('sub1', 'image', data) context.send('sub2', 'image', data) inputs={ "pwm_commands": PWMCommands, # Seed random number generator "seed": int, # Reset request "reset": type(None), # Render request - produces image "render_image": type(None), # Step physics "step_physics": float, # Dump state information "dump_state": float, }, outputs={ "image": JPGImage, "state_dump": Any, "reset_ack": type(None), "step_physics_ack": type(None), "episode_start": EpisodeStart, } ```
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/idea-composition.md
idea-composition.md
## Time representation * Reference clock frame: "epoch", "simulation episode" clock: hostname ## Uncertainty Optionally you can specify a second time instant, successive to the first, which defines the upper bound of the time. ## Type of timing info For sensor data: * "Last acquisition time": timestamp of the last acquired data * "Computed time": when this data was computed. * "Received" ## Wire representation ```json { "topic": "topic", "data": "data", "timing": { "acquired": { "obstopic1": {}, "obstopic2": {}, }, "computed": { "node1": {}, "node2": {}, "node3": {}, }, "received": { "frame": "sim", "time": {'s': 0, 'us': 1111}, "clock": "host1" }, } } ``` ## Advancing time ## API In Python: ```python from typing import * class Timestamp: s: int us: int class TimeSpec: time: Timestamp time2: Optional[Timestamp] frame: str clock: str class TimingInfo: acquired: Optional[Dict[str, TimeSpec]] processed: Optional[Dict[str, TimeSpec]] received: Optional[TimeSpec] def on_received_topicname(self, context, data, timing: TimingInfo): pass ```
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/idea-timestamping.md
idea-timestamping.md
# AIDO Nodes Protocol {#part:aido-protocol status=ready} This document describes the rationale and design for the AIDO protocol. <div id="toc"></div> # Goals and non-goals {status=ready} ## Goals ### Long shelf life We want to obtain a library of modules that have a long "shelf life". For example, it should be easy to run "the line detector from 2018" in 2021. This also suggests that modules should be independent of middle-ware as much as possible. ### Flexibility It should be possible to easily use a module in at least these scenarios: * On the robot in real-time. * Called as part of other modules ("module decorator"). * In a simulation, with the simulator both local (same host) or remote. * In "batch mode", where the data is supplied from logs. It should be possible to run two instances of the same module / system on the same host. ### Deterministic replay It should be possible to apply the same module to the same data and obtain the same output. Example violation: current Slimremote protocol runs simulation while it "waits" for the connection from the client. The result is then dependent on the network status. ### Deterministic uncertainty. There should be a clear way for modules to access a seed to use for their random number generators. ### Protocol checks It should be explicit what protocol a module uses, and it should be easy to check to avoid incompatibilities. Example: Understanding whether I can pipe `p1` into `p2`. ### Resource limitation Should be possible to give hard constraints on memory/cpu for each node. ### Protocol extendability The protocols should support a notion of extension; so that we can say that not only `p1` is different from `p2`, but also that any agent using `p1` would work with `p2`. ### Meta information Nice to have some meta information in the module (who wrote, the description, etc.) ## Non-goals {status=ready} ### Ultimate speed. We are OK in accepting a performance hit. (Note: did you know it takes 20ms to deserialize the line segment messages with ROS?) ## Why ROS is not a solution "Using ROS" is not a solution, due to the following problems. ### Network trouble ROS insists on having two processes need to know the other hosts not only by IP, but also by hostname. This causes a bunch of problems. ### Incompatibility ROS 1 does not allow Python 3. ### Non-compositionality It is not possible to run two ROS independent instances of a system on the same machine. # AIDO Nodes {status=ready} ## Overview We go back to the UNIX philosophy. "AIDO Nodes" or simply "nodes" are executable that read and write to `stdin` and `stdout`. The nodes are likely packaged in a Docker container. From our point of view, it does not matter whether we are running a naked executable or a containerized executable. In either case, there will be a standard input / standard output to write to. The data that is moved across these sockets is encoded as JSON-L: each line is a well-formed JSON message. JSON also allows to add binary data, encoded as a base64 string. AIDO Nodes interact according to well-defined protocols that are formally specified. There are two levels of formalization: 1. Describe which messages are valid messages. For this, we use JSON Schema. 2. Describe what is a valid interaction or sequence of messages. For this, we use a regular language. ## Individual JSON messages The messages are of the form: ```json {"topic": ![topic name], "data": ![data]} ``` A newline delimiter separates the JSON messages. The "topic name" has the same semantics as in ROS: while there is only one pipe for stdin/stdout, there are different logical streams of data that are labeled with a topic name. ## Formalizing the protocol To define a protocol, we need to specify: 1. What are the input and output channels. 2. For each channel, what is the data format. 3. What valid sequence of messages are accepted. Examples: * An agent of type P1 accepts a sequence of images and outputs a series of commands ("left", "right" velocity signals). * An agent of type P2 accepts intrinsic and extrinsic image calibration data followed a sequence of images and outputs a series of commands ("left", "right" velocity signals). * An agent of type P3 accepts intrinsic and extrinsic image calibration data, a kinematic calibration file, followed a sequence of images and outputs a series of commands ("left", "right" PWM signals). * An agent of type P4 accepts extrinsic image calibration data, a kinematic calibration file, followed a sequence of *rectified* images and outputs a series of commands ("left", "right" PWM signals). All of these are slighly different and failure of distinguishing between those caused much pain. Note that once we have these formalized, we can also do automatic conversion of protocols. ("If you have an agent of type P1, you can create an agent of type P2 by..."".) ## Language describing the interaction One way to formalize the interaction protocols are via regular languages. We use this syntax: * Define `in:![channel]` as denoting the event "a message was received on channel `![channel]`". * Define `out:![channel]` as denoting the event "a message was produced on channel `![channel]`". * Define `L*` as "Zero or more repetitions of `L`". * Define `L?` as "Zero or one repetitions of `L`". * Define `L+` as "One or more repetitions of `L`". * Define `A;B;C` as "`A` followed by `B` followed by `C`" * Define `A|B|C` as "either `A` or `B` or `C`" For example, consider the following protocol: "An agent that follows the protocol `LaneFilter` accepts one CameraCalibration message on the channel `calibration`, followed by any number of images on the channel `image`, and to each image it will reply with a pose estimate on channel `estimate`." As a formal language this can be written as: ``` LaneFilterLanguage := in:calibration (in:image ; out:estimate)* ``` This is then a formal description of the protocol; not only the data format, but also of the behavior of the component. ## User APIs Much of the complexity is hidden for the user. ### Defining protocols using `InteractionProtocol` Use the class `InterctionProtocol`. See `aido_nodes.protocols` for the currently defined protocols. Here is an example: ```python from zuper_nodes import InteractionProtocol from aido_schemas import JPGImage protocol_image_filter = InteractionProtocol( description="""Takes an image, returns an image.""", inputs={"image": JPGImage}, outputs={"transformed": JPGImage}, language=" (in:image ; out:transformed)*" ) ``` Above, `JPGImage` is a regular Python dataclass. The JSON schema description will be generated from the Python dataclass annotations. ### Creating nodes that follow the protocol There is an API that allows to easily create a node that follows the protocol while hiding all the complexity of JSON decoding/encoding. A minimal "image filter" can be realized as follows: ```python from aido_schemas import JPGImage, protocol_image_filter, wrap_direct class DummyFilter: protocol = protocol_image_filter def on_received_image(self, context, data: JPGImage): transformed = data # compute here context.write("transformed", transformed) if __name__ == '__main__': node = DummyFilter() wrap_direct(node=node, protocol=node.protocol) ``` The user must implement for each input channel `![channel name]` the function `on_received_![channel name]`. This function will be called with parameters `data`, containing the data received (already translated from JSON), and an object `context`. The object `context` provides the methods: ```python # write to the given output channel context.write('channel', data) # log something context.log('log string') ``` If the node implements it, the API will also call the function `init()` at the beginning and `finish()` at the end. ### Guarantees The node can assume that the sequence of calls will respect the protocol. For example, if the protocol is: ```in:calibration ; (in:image ; out:estimate)``` the node can assume that there is going to be a call to `on_received_calibration` before any call to `on_received_image`. On the other hand, note that the node itself must respect the protocol that has been declared. ## Dockerization examples See the folder `minimal` in this repository for the minimal implementation of the protocols so far defined. ## Extra features: configuration handling If the node has an attribute called `config`, then the API automatically exposes that configuration. For example, suppose the node is the following: ```python from aido_nodes import protocol_image_filter, JPGImage class MyConfig: num_frames: int = 3 class MyFilter: config: MyConfig = MyConfig() protocol = protocol_image_filter def on_received_image(self, context, data: JPGImage): ... def on_updated_config(self, context, key, value): context.log(f'Config was updated: {key} = {value!r}') ``` Then the node will also respond to "control" messages in the channel "`wrapper.set_config`" of the form: ```json {"topic": "wrapper.set_config", "data": {"key": "![config key]", "value": ![config value]}} ``` For example, in this case we can send a message like: ```json {"topic": "wrapper.set_config", "data": {"key": "num_frames", "value": 2}} ``` The API will automatically update the field `node.config.num_frames`. Then it will call (if defined) the function `on_updated_config()`; useful if something needs to be re-initialized. ## More complicated example of language Consider the protocol called `aido_nodes.protocol_image_source`: ```python protocol_image_source = InteractionProtocol( inputs={"next_image": type(None), # ask for the next image "next_episode": type(None)}, # ask for the next episode outputs={"image": JPGImage, # the output data "episode_start": EpisodeStart, # marks the start of episode "no_more_images": type(None), "no_more_episodes": type(None)}, interaction=parse_language(""" ( in:next_episode ; ( out:no_more_episodes | (out:episode_start ; (in:next_image ; (out:image | out:no_more_images))*) ) )* """), ) ``` `type(None)` means that those messages do not carry any payload. The informal description is: 1) First, the node expects to receive a `next_episode` message to start the episode. 2) To this, it can respond either with `no_more_episodes` or `episode_start`. 3) Then it will expect messages `next_image` to which it will reply either with an `image` or with `no_more_images`. <!-- The nondeterministic finite automaton for the language is parsed as in [](#example_language1): <figure id='example_language1'> <img src="aido-protocol.assets/example_language1.svg"/> <figcaption> In this diagram, "always" corresponds to an automatic transition. </figcaption> </figure> --> ## Gains from formal definition {status=beta} We can then use the usual machinery of the field of formal languages to reason about composition and extendability. ### Extending interaction protocol For example, we can describe backward-compatibility extensions of protocols. Imagine that there is a lane filter who can also accept IMU data. But not always it will provide an updated pose from the IMU data. Its language would be: ``` LaneFilterLanguage2 := in:calibration ( (in:image out:estimate) | (in:IMU out:estimate? ))* ``` It is possible (with some assumptions) to reason that LaneFilterLanguage1 is a sublanguage of LaneFilterLanguage2, so that an aidonode that implements the second can be used where the first would be used. ### Extending messages Another possibility is where the data type is extended. Already from JSON schema we have a notion of partial order. For example imagine a message with two fields: ```json {"field1": ..., "field2": ...} ``` Adding a field should be a backward compatible change (we did this a few times with AIDO). ```json {"field1": ..., "field2": ..., "extra_field": ...} ``` Here is how it looks like in JSON Schema. Note that JSON Schema also allows defining various constraints (apart from the type, also minimum/maximum values etc.) The first schema is: ```json { "title": "Message v1", "description": "First version of the messages", "type": "object", "fields": { "field1": { "type": "integer", "exclusiveMinimum": 0, }, "field2": { "type": "string" } } } ``` The second schema is: ```json { "title": "Message v1", "description": "First version of the messages", "type": "object", "fields": { "field1": { "type": "integer", "exclusiveMinimum": 0, }, "field2": { "type": "string" }, "extra_field": { "type": "string" } } } ``` ## More detailed architecture {status=draft} ### ROS wrapper <figure id="fig:wrapper"> <img src="aido-protocol.assets/image-20190210152739118.png"/> </figure> ### Batch processing <figure id="fig:batch"> <img src="aido-protocol.assets/image-20190210153222688.png"/> </figure> <style> img { max-width: 100%; } </style>
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/protocol.md
protocol.md
# import json import timeit import cbor2 import cbor import numpy as np import pybase64 as base64 import ujson as json def bytes_to_json(jpg_bytes: bytes) -> str: data = { 'jpg_bytes': base64.b64encode(jpg_bytes).decode('ascii') } return json.dumps(data).encode('utf-8') def bytes_to_cbor(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': jpg_bytes, } return cbor.dumps(data) def bytes_to_cbor_b64(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': base64.b64encode(jpg_bytes).decode('ascii') } return cbor.dumps(data) def bytes_to_cbor2(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': jpg_bytes, } return cbor2.dumps(data) def bytes_to_cbor2_b64(jpg_bytes: bytes) -> bytes: data = { 'jpg_bytes': base64.b64encode(jpg_bytes).decode('ascii') } return cbor2.dumps(data) def get_jpg_image(shape) -> bytes: H, W = shape values = (128 + np.random.randn(H, W, 3) * 60).astype('uint8') jpg_data = bgr2jpg(values) return jpg_data def bgr2jpg(image_cv) -> bytes: import cv2 # noinspection PyUnresolvedReferences compress = cv2.imencode('.jpg', image_cv)[1] jpg_data = np.array(compress).tostring() return jpg_data N = 3 shape = (480 * N, 640 * N) test_image: bytes = get_jpg_image(shape) # f = open('stream.bin', 'wb') def test1(): """ JSON with base64""" res = bytes_to_json(test_image) def test2(): """ CBOR with base64""" res = bytes_to_cbor_b64(test_image) def test3(): """ CBOR with built-in bytes""" res = bytes_to_cbor(test_image) def test4(): """ CBOR2 with base64""" res = bytes_to_cbor2_b64(test_image) def test5(): """ CBOR2 with built-in bytes""" res = bytes_to_cbor2(test_image) number = 800 for f in [test3, test2, test4, test5, test1,]: f() # warmup duration = timeit.timeit(f, number=number) latency_ms = duration / number * 1000 size = '%d KB' % (len(test_image) / 1024) print(f'{f.__doc__}: shape {shape} ({size}) latency = {latency_ms} ms') # # duration = timeit.timeit(test2, number=number) # # latency_ms = duration / number * 1000 # size = '%d KB' % (len(test_image) / 1024) # print(f'CBOR encoding: shape {shape} ({size}) latency = {latency_ms} ms') # # with open('test_vector.jpg', 'wb') as f: # f.write(test_image)
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/performance.py
performance.py
Minimal node protocol ==================== The node must support the following. ## Basic protocol The wires contain a sequence of CBOR messages. Each message is a dictionary. ## Basic control mechanism To every message the node responds with one of the two messages "understood", or "not understood". If understood: ```yaml control: understood ``` If not understood: ```yaml control: not-understood data: optional message string ``` In this case, the other party should not expect any result. Then there is a sequence of messages, terminated with a sequence marker: ```yaml control: over ``` ## Get capabilities The node might receive a `capabilities` message, whose `data` dictionary contains a dictionary. The semantics of these depend on the interaction. ```yaml control: capabilities data: z2: protocol-reflection: true ``` The node must respond with the sequence: ```yaml - control: understood - control: capabilities data: z2: protocol-reflection: true - control: over ```
zuper-nodes
/zuper-nodes-2.0.3.tar.gz/zuper-nodes-2.0.3/docs/protocol-hs.md
protocol-hs.md
from setuptools import setup, find_packages def get_version(filename): import ast version = None with open(filename) as f: for line in f: if line.startswith('__version__'): version = ast.parse(line).body[0].value.s break else: raise ValueError('No version found in %r.' % filename) if version is None: raise ValueError(filename) return version version = get_version('src/zuper_schemas/__init__.py') import os description = """""" def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='zuper-schemas', version=version, package_dir={'': 'src'}, packages=find_packages('src'), zip_safe=True, entry_points={ 'console_scripts': [ ] }, install_requires=[ ], )
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/setup.py
setup.py
from typing import NewType from .physical import UnitQuantity from .utils import dataclass ISODateString = NewType('ISODateString', str) @dataclass class Date: iso: ISODateString @dataclass class TimeInterval: value: UnitQuantity
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/timing.py
timing.py
from dataclasses import field from typing import * from .utils import dataclass PythonPackageName = str @dataclass class Version: major: str minor: str patch: str @dataclass class Exact: exact: Version @dataclass class VersionBound: minimum_version: Version maximum_version: Version VersionRequirement = Union[Exact, VersionBound] @dataclass class PythonRequirement: package_name: PythonPackageName version_requirement: Optional[VersionRequirement] @dataclass class PythonEnvironmentRequirements: python_version: VersionRequirement package_requirements: List[PythonRequirement] = field(default_factory=[])
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/python_packages.py
python_packages.py
from zuper_schemas.physical import UnitQuantity, UnitString, Unit from .utils import dataclass @dataclass class MonetaryValue: value: UnitQuantity unit_USD = UnitString('USD') unit_BTC = UnitString('BTC') import decimal def value_USD(x): return UnitQuantity(decimal.Decimal(x), Unit(unit_USD)) def value_BTC(x): return UnitQuantity(decimal.Decimal(x), Unit(unit_BTC)) def BTC_from_USD(usd: UnitQuantity) -> UnitQuantity: pass
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/monetary.py
monetary.py
# language=markdown """ # An indexing service An indexing service function is defined by: 1) A type 2) A query string For example, suppose that we wanted somebody to keep track of cached functions. We have FunctionCalls: FC(f, params) A FunctionResult (FR) is of the type: FR(fc, data, assumptions) For example: FR -- fc --> FC -- data --> D -- assume --> Assumptions So signed by a computer C we have: SFR -fr--> FR --fc--> FC | |---> D v `---> A C """ from collections import defaultdict from typing import Callable, TypeVar, Set, Dict, Any from .utils import Generic, dataclass # from zuper_schemas.computation import AbstractFunctionCall from .computation import AbstractFunctionCall, FunctionResult # from zuper_schemas.core import FunctionResult from .crypto import Signed, PublicKey from mypy_extensions import NamedArg """ If we want to cache this by result FC we would have CachingService: thing_nature: @SFR key: {fr: fc} """ T = TypeVar('T') K = TypeVar('K') # accept_interface = Callable[[NamedArg(T, 'candidate')], bool] # index_interface = Callable[[NamedArg(T, 'candidate')], K] accept_interface = Any index_interface = Any @dataclass class CachingCriteria(Generic[T, K]): accept: accept_interface indexby: index_interface # store_interface = Callable[[NamedArg(T, 'candidate')], bool] # query_interface = Callable[[NamedArg(K, 'key')], Set[T]] store_interface = query_interface = Any @dataclass class CachingService(Generic[T, K]): criteria: CachingCriteria[T, K] # how we are going to get it? owner: PublicKey store: store_interface query: query_interface def accept_all_SFR(*, candidate: Signed[FunctionResult]) -> bool: return True def index_by_function_call(*, candidate: Signed[FunctionResult]) -> AbstractFunctionCall: return candidate.data.fc fc_caching_criteria = CachingCriteria[Signed[FunctionResult], AbstractFunctionCall]( accept=accept_all_SFR, indexby=index_by_function_call) class ConcreteCachingService(Generic[T, K]): def __init__(self, criteria: CachingCriteria): self.values: Dict[K, Set[T]] = defaultdict(set) self.owner = None self.criteria = criteria def store(self, *, candidate: T): if self.criteria.accept(candidate=candidate): k = self.criteria.indexby(candidate=candidate) self.values[k].add(candidate) def query(self, *, key: K): return self.values[key] @classmethod def examples(cls, self): fc_concrete_service = ConcreteCachingService[Signed[FunctionResult], AbstractFunctionCall](fc_caching_criteria) """ I provide function caching service for command results for $1 / query. ~CodesignProblem: requires: ~RTuple: transfer: ~TransferTo: value: 1 USD dest: $identity provides: ~FTuple: service: ~FunctionCachingService: caching_service: accumulation_channel: query_channel: ~CachingService: thing_nature: @FunctionCall key: ~KeyMultiple: identifier: fr child: ~KeySingle: fc """ """ A cache of CachingServices """
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/indexing.py
indexing.py
from typing import * from zuper_schemas.git import GitRepository from zuper_schemas.network import URL from zuper_schemas.timing import Date from .utils import dataclass, Identifier @dataclass class GithubView: organizations: Dict[str, 'GithubOrganization'] @dataclass class GithubUser: id: int url: URL gravatar_id: Optional[str] # # organization_self: GithubOrganization # organizations: Set[GithubOrganization] @dataclass class GithubRepository: id: int node_id: str full_name: str private: bool # fork: Optional['GithubFork'] visibility: str creator: GithubUser created: Date updated: Date fork_count: int watchers_count: int git_repository: GitRepository # # @dataclass # class GithubFork: # repository: GithubRepository # repository_version: Any @dataclass class GithubOrganization: id: int node_id: str url: URL avatar_url: URL repositories: Dict[Identifier, GithubRepository] @dataclass class GithubCredentials: username: str password: str class UIProxy(): def ask(self, msg) -> Dict[str, str]: pass def get_user_proxy() -> UIProxy: pass # @sideeffect def ask_user_credentials(): msg = 'Please write your username and password' uiproxy = get_user_proxy() res = uiproxy.ask(msg) username = res['username'] password = res['password'] return GithubCredentials(username, password) # def get_github_view() -> GithubView: # credentials = ask_user_credentials() # authenticate = None # view = authenticate(credentials) # return view
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/github.py
github.py
from .utils import dataclass, Generic # @dataclass # class ConcreteResult: # no jobs in side # content: Any # # # @dataclass # class ConcreteCallable: # pass # # # @dataclass # class LocalPythonFunction(ConcreteCallable): # python_function: str # # # @dataclass # class FunctionCall: # callable: FunctionDefinition # parameters: Dict[str, Any] # # def __call__(self, **kwargs): # callable = ExpectFunctionDefinition(implementations={}, function_call=self) # return FunctionCall(callable=callable, parameters=kwargs) # # # # @dataclass # class ExpectFunctionDefinition(FunctionDefinition): # function_call: FunctionCall # # @dataclass # class Node: # pass # # @dataclass # class CurrentNode(Node): # pass # # @dataclass # class Context: # node: Node # time: float # # # def lookup_from_context(*, context: Context, identifier: str) -> Context: # pass # # # def F(f): # assert isinstance(f, Callable), f # f0 = FunctionDefinition(implementations={'python': LocalPythonFunction(python_function=f.__name__)}) # # def f2(*args, **kwargs): # if args: # msg = 'Cannot call this with positional arguments: %s %s' % (f, args) # raise TypeError(msg) # return FunctionCall(callable=f0, parameters=kwargs) # # return f2 # # # def zuper_link_resolve(*, context: Context, link: IPDELink) -> Any: # if '/' in link: # i = link.index('/') # first = link[:i] # rest = link[i + 1] # else: # first = link # rest = IPDELink('') # # context2 = F(lookup_from_context)(context=context, identifier=first) # # if rest: # return F(zuper_link_resolve)(context=context2, link=rest) # else: # return context2 # # # class DNS: # pass # # # def lookup(*, context: Context, first: Identifier, rest: str = None): # rest = rest or [] # dns_lookup = F(zuper_link_resolve)(context=context, link=IPDELink("@Instance/api/dns/lookup")) # resolved = dns_lookup(domain=first, record="txt") # return F(zuper_link_resolve)(context=resolved, link=rest) # # def zm_resolve_callable(link) -> Callable: # pass # # # class LookupInterface: # def __call__(self, domain: Domain, record: str) -> Optional[str]: # return '' # # def lookup(domain: Domain, origin: Node, time: Timespec ): # dns_lookup: LookupInterface = zm_resolve_callable("@Instance/api/dns/lookup") # # record = dns_lookup(domain=domain, record='txt') # # # # class Root: # ipde = 0 # @Executable: # # @Executable/Python: # # @Executable/Program: # docker: @DockerExecution # # # @Alert: # message: # location?: # # @Alert/Warning: # # @Alert/Error: # # # @JobResult: # job: @Job # warnings: @list(@Warning) # # console_output: @ConsoleOutput # # @ConsoleOutput: # stderr: @ConsoleOutputStream # stdout: @ConsoleOutputStream # # @ConsoleOutputStream: # previous?: @ConsoleOutputStream # line: @bytes # # # @JobResult/EvaluationFailure: # # # @JobResult/Success: # result: @ # # @JobResult/Failure: # errors: @list(@Errors) # # @JobResult/Failure/PartialFailure: # partial_result: @ ####### # #@TypedData: # size: @int # mime_type: @string # encoding: @string ########### # # @IPCLSegment: # # @IPCLSegment:Resolution: # # # @IPCLSegment:IPNSSegment: # ipns: @multihash # # @IPCL: # elements: @list(IPCLSegment) # # @Link: # # @Link/ZuperLink: # Cid: @cid # IsData: @bool # IsMeta: @bool # IsHistory: @bool # CurrentMetaSize: @int # HistoryMetaSize: @int # CurrentDataSize: @int # HistoryDataSize: @int # # @Link:LinkToIPCL: # ipcl: @IPCL # type: # # @Link:LinkToVersion: # entity: @Entity # value: @ # # @Link:LinkToJob: # job: @Job # expect-shape: @Shape # # @Link:LinkToJobResult: # job_result: @JobResult # expect-shape: @Shape # # @HashResult: # algorithm: @string # results: @bytes # # @AES_Encrypted: # payload: @TypedData # with mime=der # key-hash: @HashResult # # @SecretSharedKey: # key-hash: @HashResult # plain: @bytes # # @EncryptedFor: # dest: @PublicKey # payload: @bytes # # @PublicKey: # content: @TypedData # private?: @PrivateKey # # @PrivateKey: # content: @TypedData # # @SignedEnvelope: # data: @ # signature: @Signature # # @Signature: # key: @PublicKey # result: @bytes # # # @ClockReference: # # # # # published at public key # @ArbiterInfo: # keys: @dict(QueueInfo) # # @QueueInfo: # last: @VersionInfo # link to last version # queues: @list(Queue) # # @Queue:Pubsub: # topic: @string # # @Queue:Websocket: # url: @url #
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/core.py
core.py
# import zuper_json from datetime import datetime from typing import * from zuper_json.zeneric2 import resolve_types from .utils import dataclass, Generic if TYPE_CHECKING: from dataclasses import dataclass X = TypeVar('X') @dataclass class PublicKey: ID: str # Qm.... pem: str # recovery: 'Optional[EncryptedClearType[Any]]' = None @dataclass class EncryptedClearType(Generic[X]): pub: PublicKey encrypted_session_key: bytes ciphertext: bytes tag: bytes nonce: bytes @dataclass class PrivateKey: ID: str # hash of public key pem: str refs = (PublicKey, PrivateKey, EncryptedClearType) resolve_types(EncryptedClearType, refs=refs) resolve_types(PublicKey, refs=refs) # print('OK here') @dataclass class Signed(Generic[X]): pub: PublicKey sig: bytes data: X time: datetime @dataclass class Pin(Generic[X]): data: X valid_from: datetime valid_to: datetime # # @dataclass # class SymmetricKey: # key: bytes # # # @dataclass # class SymmetricallyEncrypted(Generic[X]): # key_hash: Multihash # encoded: bytes
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/crypto.py
crypto.py
from typing import ClassVar, Optional, Any, List, Dict, Union from .utils import dataclass @dataclass class JSONSchema: _dollar_schema: ClassVar[str] = "http://json-schema.org/schema#" title: Optional[str] description: Optional[str] default: Optional[Any] examples: List[Any] enum: Optional[List] const: Optional[Any] definitions: Optional[Dict[str, 'JSONSchema']] @dataclass class JSONSchemaInt(JSONSchema): _type: ClassVar[str] = "int" multipleOf: int @dataclass class JSONSchemaBool(JSONSchema): _type: ClassVar[str] = "boolean" @dataclass class JSONSchemaNull(JSONSchema): _type: ClassVar[str] = "null" @dataclass class JSONSchemaNumber(JSONSchema): _type: ClassVar[str] = "number" multipleOf: float minimum: Optional[float] maximum: Optional[float] exclusiveMinimum: Optional[bool] exclusiveMaximum: Optional[bool] pattern = str @dataclass class JSONSchemaArray(JSONSchema): _type: ClassVar[str] = "array" items: Optional[Union[JSONSchema, List[JSONSchema]]] contains: Optional[JSONSchema] additionalItems: Optional[bool] minItems: Optional[int] maxItems: Optional[int] uniqueItems: Optional[bool] @dataclass class JSONSchemaString(JSONSchema): _type: ClassVar[str] = "string" pattern: Optional[pattern] maxLength: Optional[int] minLength: Optional[int] format: Optional[str] @dataclass class JSONSchemaObject(JSONSchema): _type: ClassVar[str] = "object" required: List[str] properties: Dict[str, JSONSchema] propertyNames: Optional[JSONSchemaString] additionalProperties: Optional[Union[bool, JSONSchema]] # XXX minProperties: Optional[int] maxProperties: Optional[int] dependencies: Optional[Dict[str, List[str]]] patternProperties: Optional[Dict[pattern, JSONSchema]] @dataclass class JSONSchemaAnyOf(JSONSchema): anyOf: List[JSONSchema] @dataclass class JSONSchemaAllOf(JSONSchema): allOf: List[JSONSchema] @dataclass class JSONSchemaOneOf(JSONSchema): oneOf: List[JSONSchema] @dataclass class JSONSchemaNot(JSONSchema): _not: List[JSONSchema] @dataclass class JSONSchemaRef(JSONSchema): _dollar_ref: str
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/json_schema.py
json_schema.py
# from abc import ABCMeta, abstractmethod # # from dataclasses import dataclass # from typing import * # # X = TypeVar('X') # # # def example(): # @dataclass # class User: # age: int # name: str # # def load(name: str) -> User: # pass # # def youngest(u1: User, u2: User): # if u1.age < u2.age: # return u1 # else: # return u2 # # def family_young() -> User: # u1 = load('u1') # u2 = load('u2') # return youngest(u1, u2) # # # Proof[ family_young = X ]: # # Proof[ load('u1') = X ] + # # Proof[ load('u2') = Y | load('u1') = X ] + # # Proof[ X.age < Y.age | load('u1') = Y AND load('u2') = X ] # # OR # # Proof[ load('u1') = Z ] + # # Proof[ load('u2') = X | load('u1') = Z ] + # # Proof[ X.age < Z.age | load('u1') = Y AND load('u2') = X ] # # # Proof[ X.age < Y.age | load('u1') = X | load('u2') = Y ] # # OR Proof[ Y.age < A.age | load('u1') = Y | load('u2') = X ] # # # assuming no side effects: # # # # Proof[ X.age < Y.age | load('u1') = X, load('u2') = Y ] # # OR Proof[ Y.age < A.age | load('u1') = Y, load('u2') = X ] # # # # # # def LEQ(a: X, b: X) -> type: # """ The proposition a <= b is a Type""" # # @dataclass # class Leq: # a: ClassVar[X] # b: ClassVar[X] # proof: Any # # return Leq # # # def get_proof(): # why = 'My explanation' # return LEQ(1, 2)(proof=why) # # # @dataclass # class NLEQ(Generic[X]): # a: X # b: X # # # class Impossible: # """ Empty set """ # # def __init__(self): # assert False # # # class PosetStructure(Generic[X], metaclass=ABCMeta): # the_set: ClassVar[Type[X]] # # @abstractmethod # def leq(self, a: X, b: X) -> Union[LEQ[X], NLEQ[X]]: # ... # # # P = TypeVar('P', bound=PosetStructure) # # # class OppositePoset(PosetStructure[X]): # P0: PosetStructure[X] # # def leq(self, a: X, b: X) -> Union[LEQ[X], NLEQ[X]]: # return self.P0.leq(b, a) # # # strategy: Callable[[], Prop] # # # def leq(a: P, b: Inv[P]) -> LEQ[P]: # P = type(a) # assert P.leq(a, b) # return LEQ(a, b) # # # def leq_proof(hints) -> Certificate[LEQ[P]]: # pass # # # class Integers(Poset): # pass # # # P = TypeVar('P', bound=Poset) # # # class PosetRelation(Generic[P]): # a: P # b: P # # # class VerifiedStatement: # statement: Statement # proof: Proof # # # def test_1(): # pass # # # @dataclass # class Placeholder(Generic[X]): # guid: str
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/posets.py
posets.py
import typing from dataclasses import dataclass from typing import Optional, Any, List, Union from zuper_json.zeneric2 import resolve_types from .crypto import PublicKey, Signed from .utils import Generic @dataclass class SecurityModel: # guid: Any owner: PublicKey writer: PublicKey arbiter: PublicKey X = typing.TypeVar('X') M = typing.TypeVar('M') N = typing.TypeVar('N') Y = typing.TypeVar('Y') W = typing.TypeVar('W') Z = typing.TypeVar('Z') @dataclass class Entity(Generic[X]): guid: str security_model: SecurityModel forked: 'Optional[Entity[X]]' = None parent: 'Optional[Entity[Any]]' = None resolve_types(Entity) # # @dataclass # class User: # name: str # born: int # # # class Y(Entity[User]): # @classmethod # def get_examples(cls, seed=None): # pks = PublicKey.get_examples(seed=seed) # # while True: # _, pk1 = pks.__next__() # _, pk2 = pks.__next__() # # security_model = SecurityModel(owner=pk1, arbiter=pk2) # guid = "guid" + str(random.randint(100, 1000)) # data0 = User(name='John', born=1990) # e = Y(guid=guid, # data0=data0, # security_model=security_model) # yield guid, e # setattr(X, 'get_examples', get_examples) # remember_created_class(Y) @dataclass class EntityVersion(Generic[M]): entity: Entity[M] value: M previous: 'Optional[EntityVersion[M]]' = None # resolve_types(EntityVersion, locals()) # contains the chain of operations @dataclass class EntityOperationSetKey: key: str value: Any EntityOperation = Union[EntityOperationSetKey] def apply_operation_inplace(value, operation: EntityOperation): if isinstance(operation, EntityOperationSetKey): setattr(value, operation.key, operation.value) else: raise NotImplementedError(operation) def apply_operation(value: Any, operation: EntityOperation) -> Any: import copy if isinstance(operation, EntityOperationSetKey): value2 = copy.deepcopy(value) setattr(value2, operation.key, operation.value) return value2 else: raise NotImplementedError(operation) @dataclass class VersionChain(Generic[N]): operations: List[EntityOperation] version: EntityVersion[N] previous: 'Optional[VersionChain[N]]' = None @dataclass class EntityUpdateProposal(Generic[Y]): base: EntityVersion[Y] operations: List[EntityOperation] # consistent: bool depends: 'Optional[EntityUpdateProposal[Y]]' = None @dataclass class VersionChainWithAuthors(Generic[Z]): version: VersionChain[Z] signed_proposals: List[Signed[EntityUpdateProposal[Z]]] previous: 'Optional[VersionChainWithAuthors[Z]]' = None @dataclass class EntityState(Generic[W]): data: W v: EntityVersion[W] vc: VersionChain[W] vca: VersionChainWithAuthors[W] # # @dataclass # class Rejection: # operation: EntityUpdateProposal # conflicts: Optional[EntityUpdateProposal] # # # @dataclass # class EntityMerge: # entity: Entity # previous: Optional['EntityMerge'] # accepted: List[EntityUpdateProposal] # rejected: List[Rejection] # # @EntityOperation:AddOwner: # owner: @PublicKey # # @EntityOperation:RemoveOwner: # owner: @PublicKey # # @EntityOperation:AddArbiter: # owner: @PublicKey # # @EntityOperation:RemoveArbiter: # owner: @PublicKey # # @EntityOperation:AddWriter: # owner: @PublicKey # # @EntityOperation:RemoveWriter: # owner: @PublicKey # # @EntityOperation:AddReader: # owner: @PublicKey # # @EntityOperation:RemoveReader: # owner: @PublicKey
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/chain.py
chain.py
from .utils import dataclass from typing import NewType, List, ClassVar DecimalString = NewType('DecimalString', str) # @dataclass @dataclass class Decimal: value: DecimalString examples: ClassVar[List['Decimal']] = [] Decimal.examples = [ Decimal(DecimalString('1')), Decimal(DecimalString('3.14')), ]
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/numbers.py
numbers.py
from .utils import dataclass from typing import NewType, ClassVar, List from zuper_schemas.numbers import Decimal, DecimalString UnitString = NewType('UnitString', str) @dataclass class Unit: name: UnitString examples: ClassVar[List['Unit']] = [] Unit.examples = [ Unit(UnitString('m')), Unit(UnitString('m/s')) ] @dataclass class UnitQuantity: value: Decimal units: Unit examples: ClassVar[List['UnitQuantity']] = [] UnitQuantity.examples = [ UnitQuantity(Decimal(DecimalString('12')), Unit(UnitString('m'))), UnitQuantity(Decimal(DecimalString('12.1')), Unit(UnitString('m/s'))) ]
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/physical.py
physical.py
from .utils import dataclass # # @DockerExecution: # image: @DockerImage # environment: @dict(@string) # entrypoint?: # command: @list(@string) # # @DockerComposeConfiguration: # directory: @Directory # services: @dict(@DockerExecution) # # # @DockerView: # organizations: @dict(@DockerOrganizations) # # # @Dockerfile: # commands: @list(@DockerCommands) # # @DockerDaemon: # containers: @dict(@DockerContainers) #
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/docker.py
docker.py
# # assoc(d, key, value[, factory]) Return a new dict with new key value pair # dissoc(d, *keys) Return a new dict with the given key(s) removed. # assoc_in(d, keys, value[, factory]) Return a new dict with new, potentially nested, key value pair # get_in(keys, coll[, default, no_default]) Returns coll[i0][i1]…[iX] where [i0, i1, …, iX]==keys. # keyfilter(predicate, d[, factory]) Filter items in dictionary by key # keymap(func, d[, factory]) Apply function to keys of dictionary # itemfilter(predicate, d[, factory]) Filter items in dictionary by item # itemmap(func, d[, factory]) Apply function to items of dictionary # merge(*dicts, **kwargs) Merge a collection of dictionaries # merge_with(func, *dicts, **kwargs) Merge dictionaries and apply function to combined values # update_in(d, keys, func[, default, factory]) Update value in a (potentially) nested dictionary # valfilter(predicate, d[, factory]) Filter items in dictionary by value # valmap(func, d[, factory]) Apply function to values of dictionary
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/ftoolz.py
ftoolz.py
# Need to be run before the imports below def first_import_zuper_json(): # noinspection PyUnresolvedReferences import zuper_json first_import_zuper_json() # noinspection PyUnresolvedReferences from dataclasses import dataclass # noinspection PyUnresolvedReferences from typing import NewType, Generic Identifier = NewType('Identifier', str) # must_be_like_this Size = NewType('Size', int)
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/utils.py
utils.py
import itertools from unittest import SkipTest from zuper_json.monkey_patching_typing import RegisteredClasses from zuper_json.test_utils import assert_object_roundtrip, assert_type_roundtrip from zuper_ipcl import private_register def check_one_klass(T): if not hasattr(T, 'get_examples'): raise SkipTest("No examples.") f = getattr(T, 'get_examples') examples = f(seed=32) # print(f'examples: {examples}') top5 = itertools.islice(examples, 3) with private_register('classes'): assert_type_roundtrip(T, {}) #with private_register(T.__name__): for name, el in top5: data = assert_object_roundtrip(el, {}) # print(f'Testing {T}') def test_generated(): # noinspection PyUnresolvedReferences import zuper_schemas for (module, name), K in list(RegisteredClasses.klasses.items()): if 'zuper_schemas' in module.split('.'): # print(f"I know {name}") class MyCheck: def __call__(self): return check_one_klass(K) check = MyCheck() setattr(check, 'description', f'Examples for {name}') yield check
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/test_generation.py
test_generation.py
from abc import abstractmethod, ABCMeta from typing import Generic, TypeVar, Any, Dict, Callable, NewType, List from mypy_extensions import NamedArg from .chain import Entity # from .2 import Computes, X, ComputeContext, ComputableDict from .identity import Identity from .meta import Nature from .utils import dataclass, Identifier X = TypeVar('X') Y = TypeVar('Y') T = TypeVar('T') ParameterTypes = Dict[Identifier, Nature] @dataclass class SideInfo: assumptions: Dict depth: int @dataclass class ComputationResult(Generic[T]): value: T side_info: SideInfo class ComputeContext: def resolve_abstract_function(self, abstract_function) -> ComputationResult[Callable]: pass def with_placeholders(self): pass class Computes(Generic[T], metaclass=ABCMeta): @abstractmethod def compute(self, context: ComputeContext) -> ComputationResult[T]: pass def dictmap(f, d): return {k: f(v) for k, v in d.items()} def dictval(f, d): return [f(v) for v in d.values()] def side_info_merge(sides: List[SideInfo]) -> SideInfo: pass CD = Dict[Identifier, Any] @dataclass class ComputableDict(Computes[CD]): data: Dict[Identifier, Computes[Any]] def compute(self, context: ComputeContext) -> ComputationResult[CD]: res = dictmap(lambda _: _.compute(context), self.data) values = dictmap(lambda _: _.value, res) side = dictval(lambda _: _.side_info, res) return ComputationResult[CD](value=values, side_info=side_info_merge(side)) @dataclass class FunctionSignature: parameters: ParameterTypes return_type: Nature volatile: bool side_effects: bool @dataclass class AbstractFunction: signature: FunctionSignature owner: Identity guid: str # whatever the owner decides it is appropriate @dataclass class ComputingAssumptions: semantics: str @dataclass class EntityStateAssumptions: entity_state: Dict[Entity, Any] @dataclass class Assumptions: entity_state_assumptions: EntityStateAssumptions computing_assumptions: ComputingAssumptions ParametersToUse = NewType('ParametersToUse', Dict[Identifier, Any]) class AbstractFunctionCall(Computes[X]): abstract_function: AbstractFunction parameters: ComputableDict assume: ComputingAssumptions def compute(self, context: ComputeContext) -> ComputationResult[X]: crf: ComputationResult[Callable[..., X]] = context.resolve_abstract_function(self.abstract_function) crp: ComputationResult[CD] = self.parameters.compute(context) f = crf.value p: Dict[Identifier, Any] = crp.value y = f(**p) cr = side_info_merge([crf.side_info, crp.side_info]) return ComputationResult(value=y, side_info=cr) @dataclass class FunctionResult: fc: AbstractFunctionCall data: object assume: ComputingAssumptions from .utils import dataclass, Identifier @dataclass class Constant(Computes[T]): value: T def compute(self, context: ComputeContext) -> ComputationResult[T]: side_info = SideInfo({}, 0) return ComputationResult(value=self.value, side_info=side_info) @dataclass class IfThenElse(Computes[X]): """ Constraints: IfThenElse(true, a, b) = a IfThenElse(false, a, b) = a """ expr: Computes[bool] a: Computes[X] b: Computes[X] def compute(self, context: ComputeContext) -> ComputationResult[X]: eval_expr = self.expr.compute(context=context) if eval_expr.value: eb = self.a.compute(context=context) else: eb = self.b.compute(context=context) return ComputationResult(eb.value, side_info_merge([eb.side_info, eval_expr.side_info])) @dataclass class SelectAttribute(Computes[X], Generic[X, Y]): attribute: Identifier what: Computes[Y] def compute(self, context: ComputeContext) -> ComputationResult[X]: cr = self.what.compute(context) value = getattr(cr.value, self.attribute) return ComputationResult(value, cr.side_info) @dataclass class SelectEntry(Computes[X]): key: Identifier what: Computes[Dict[Identifier, X]] def compute(self, context: ComputeContext) -> ComputationResult[X]: cr = self.what.compute(context) value = cr.value[self.key] return ComputationResult(value, cr.side_info) K = TypeVar('K') V = TypeVar('V') W = TypeVar('W') # f = Callable[[NamedArg(V, name='element')], W] @dataclass class DictMap(Computes[Dict[K, W]], Generic[K, V, W]): """ Semantics: E{ DictMap(f, x) } = E{ {k: f(v) for k, f in x.items()} } For all f, x: GetAttribute(att, DictMap(f, x)) = f(GetAttribute(att, x)) """ f: Computes[Callable[[V], W]] data: Dict[K, Computes[V]] def compute(self, context) -> ComputationResult[Dict[K, W]]: fres = f.compute(context) def apply(v): fres res = dictmap(lambda _: _.compute(context), self.data) values = dictmap(lambda _: _.value, res) side = dictval(lambda _: _.side_info, res) return ComputationResult[CD](value=values, side_info=side_info_merge(side)) return {k: self.f(v.compute(context)) for k, v in self.data.items()} placeholder_guid = NewType('placeholder_guid', str) @dataclass class Placeholder(Computes[X]): name: Identifier guid: placeholder_guid def compute(self, context) -> X: return context.get_guid(self.guid) # TemplateParameters = NewType('TemplateParameters', Dict[Identifier, TemplatePlaceholder]) class SpecializeTemplate(Computes[X]): """ # Sub(Template(res, param_spec), parameters) # = # Template(res / parameters, param_spec - parameters) # # ## Simplification # # Template(x, {}) = x """ x: type pattern: ComputableDict parameters: Dict[Placeholder, Computes[Any]] def compute(self, context) -> X: context.add(self.parameters) atts = self.pattern.compute(context) Xi = type(self).__args__[0] return Xi(**atts) # #
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/computation.py
computation.py
from typing import * URL = NewType('URL', str) Domain = NewType('Domain', str) Multihash = NewType('Multihash', str) IP4 = NewType('IP4', str) IPDELink = NewType('IPDELink', str)
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/network.py
network.py
from typing import List, Optional, Dict from .utils import Identifier, dataclass @dataclass class Nature: extends: Optional[object] json_schema: object @dataclass class NatureComposite: fields: Dict[Identifier, Nature] @dataclass class NatureDict: keys: Optional[Nature] values: Optional[Nature] class NaturePrimitive(Nature): pass class NatureInt(NaturePrimitive): tests: List[str] # JSON schema tests class NatureString(NaturePrimitive): tests: List[str] # String
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/meta.py
meta.py
from typing import * from zuper_schemas.timing import Date from .utils import dataclass @dataclass class TypedData: mime: str size: int content: bytes @dataclass class LanguageSpec: code: str @dataclass class Translated: language: LanguageSpec value: str translated_from: Optional[Any] @dataclass class LocalizableString: entries: List[Translated] @dataclass class Header: long: LocalizableString short: Optional[LocalizableString] @dataclass class IndexInfo: number: bool appear_in_toc: bool @dataclass class BlockElement: pass @dataclass class Section: index_info: IndexInfo title: Optional[Header] before: Optional[List[BlockElement]] sections: List['Section'] # XXX after: Optional[List[BlockElement]] @dataclass class AuthorCredit: name: str affiliation: Optional[str] @dataclass class Document: title: Optional[Header] subtitle: Optional[LocalizableString] authors: Optional[List[AuthorCredit]] date: Optional[Date] sections: List[LocalizableString] @dataclass class ParagraphElement: pass @dataclass class Paragraph(BlockElement): translations: Dict[str, 'Paragraph'] elements: List[ParagraphElement] @dataclass class TextFragment(ParagraphElement): words: List[str] @dataclass class Figure(BlockElement): index_info: IndexInfo caption: Optional[Paragraph] contents: List[ParagraphElement] @dataclass class RasterImage: width: int height: int image_data: TypedData @dataclass class PlaceImage(BlockElement): image: RasterImage
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/documents.py
documents.py
from .crypto import PublicKey from .utils import dataclass @dataclass class Identity: name: str # any short name key: PublicKey
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/identity.py
identity.py
from typing import Dict, List, Optional from .timing import Date from .utils import dataclass, Identifier @dataclass class GitUser: name: str email: str # email class GitTreeEntry: pass class GitTree(GitTreeEntry): entries: Dict[Identifier, GitTreeEntry] class GitBlob(GitTreeEntry): blob: bytes @dataclass class GitCommit: commit_sha: str tree: GitTree parents: List['GitCommit'] commitDate: Date authorDate: Date comment: str author: GitUser committer: Optional[GitUser] # # TF = Callable[[NamedArg(int, 'b')], int] # # # def f(g: TF) -> int: # return g(2.0) + 2 # # # f2: TF = f @dataclass class GitRepository: branches: Dict[Identifier, GitCommit] tags: Dict[Identifier, GitCommit] # # diff: # ~JobPattern: # executable: /App/functions/git/diff # parameters: # current: /Commit/_/tree # previous: /Commit/_/parents/0 # # # @GitRepository: # branches: @dict(@commit) # tags: @dict(@commit) # # @GitUser: # name: @name # email: @email # # @Commit: # commit_sha: @sha # tree: @GitTree # parents: @list(@Commit) # commitDate: @date # authorDate: @date # comment: @string # author: @GitAuthor # committer?: @GitAuthor # # diff: # ~JobPattern: # executable: /App/functions/git/diff # parameters: # current: /Commit/_/tree # previous: /Commit/_/parents/0 # # # @GitTreeEntry: # # # @GitTreeEntry/GitTree: # entries: @dict(@GitTreeEntry) # # @GitTreeEntry/GitBlob: # git_blob: @sha # blob: @bytes
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/git.py
git.py
from dataclasses import dataclass from zuper_schemas.computation import AbstractFunctionCall from zuper_schemas.monetary import MonetaryValue from zuper_schemas.timing import TimeInterval from zuper_schemas.utils import Size @dataclass class ExpectType: result: object typedesc: object # TypeDescription @dataclass class Budget: latency: TimeInterval storage: Size cost: MonetaryValue @dataclass class BudgetedFunctionCall: actual: AbstractFunctionCall function_call: AbstractFunctionCall
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/budgetd.py
budgetd.py
from dataclasses import field from typing import * from zuper_json.zeneric2 import resolve_types if TYPE_CHECKING: from dataclasses import dataclass else: from .utils import dataclass Filename = NewType('Filename', str) Filepath = NewType('Filepath', str) # # @dataclass # class DirectoryEntry: # ... # # # aº = 0 # a⃖ = 0 # a⃗b = 0 # aᐩ= 0 @dataclass class File: """ A single file. """ data: bytes = field(repr=False) owner: Optional[str] = None permissions: Optional[str] = None @dataclass class Directory: """ A directory holds other directories and files. """ entries: 'Dict[str, Union[File, Directory]]' owner: Optional[str] = None permissions: Optional[str] = None __depends__ = (File, ) # # compiled: Directory # # compiled/entries/created/image # def directory_view(dirname) -> Directory: # node = ... # return node.read_directory(dirname) # # # def compile_file(data: bytes) -> bytes: # pass # # # def compile(input: Directory) -> Directory: # entries = { # 'out1': File(data=compile_file(input.entries['in1'].data)), # 'out2': File(data=compile_file(input.entries['in2'].data)), # 'out3': File(data=compile_file(input.entries['in3'].data)), # } # return Directory(entries) # # # def get_one_file(dirname: str): # input_dir: Directory = directory_view(dirname) # outdir: Directory = compile(input_dir) # # return outdir.entries['file3']
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/filesystem.py
filesystem.py
__version__ = '3.0.3' # noinspection PyUnresolvedReferences from .budgetd import * from .chain import * from .codesign import * from .computation import * from .core import * from .crypto import * from .docker import * from .documents import * from .filesystem import * from .git import * from .github import * from .identity import * from .indexing import * from .json_schema import * from .meta import * from .monetary import * from .network import * from .numbers import * from .physical import * from .posets import * from .python_packages import * from .timing import *
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/__init__.py
__init__.py
from abc import abstractmethod, ABCMeta from typing import Dict from .utils import dataclass, Identifier @dataclass class Poset: pass RTuple = Dict[Identifier, Poset] FTuple = Dict[Identifier, Poset] @dataclass class CodesignProblemInterface: provides: FTuple requires: RTuple @dataclass class ConcreteCodesignProblemInterface(CodesignProblemInterface): implementation: object @dataclass class CodesignProblem(metaclass=ABCMeta): interface: CodesignProblemInterface @abstractmethod def feasibility(self, F: FTuple, R: RTuple): pass @abstractmethod def min_resources(self, F: FTuple, R: RTuple): pass @abstractmethod def max_functionality(self, F: FTuple, R: RTuple): pass @dataclass class UncertainCodesignProblem: u: CodesignProblem l: CodesignProblem class ScalableUncertainCodesignProblem(UncertainCodesignProblem): @abstractmethod def refine(self) -> UncertainCodesignProblem: pass @abstractmethod def coarsen(self) -> UncertainCodesignProblem: pass
zuper-schemas
/zuper-schemas-3.0.3.tar.gz/zuper-schemas-3.0.3/src/zuper_schemas/codesign.py
codesign.py
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/README.md
README.md
from setuptools import setup, find_packages def get_version(filename): import ast version = None with open(filename) as f: for line in f: if line.startswith("__version__"): version = ast.parse(line).body[0].value.s break else: raise ValueError("No version found in %r." % filename) if version is None: raise ValueError(filename) return version module = "zuper_typing" line = "z5" package = f"zuper-typing-{line}" src = "src" version = get_version(filename=f"src/{module}/__init__.py") setup( name=package, package_dir={"": src}, packages=find_packages(src), version=version, zip_safe=False, entry_points={"console_scripts": []}, install_requires=[ "zuper-commons-z5", "oyaml", "pybase64", "PyYAML", "validate_email", "mypy_extensions", "typing_extensions", "nose", "coverage>=1.4.33", # "dataclasses", "jsonschema", "cbor2", "numpy", "base58", "frozendict", "pytz", "termcolor", "numpy", ], )
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/setup.py
setup.py
import logging logging.basicConfig() logger = logging.getLogger("zuper-typing") logger.setLevel(logging.DEBUG)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/logging.py
logging.py
from typing import Union import typing from zuper_typing.constants import PYTHON_36 if PYTHON_36: # pragma: no cover TypeLike = type else: TypeLike = Union[type, typing._SpecialForm]
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/aliases.py
aliases.py
import sys from typing import ClassVar PYTHON_36 = sys.version_info[1] == 6 PYTHON_37 = sys.version_info[1] == 7 NAME_ARG = "__name_arg__" # XXX: repeated ANNOTATIONS_ATT = "__annotations__" DEPENDS_ATT = "__depends__" INTERSECTION_ATT = "__intersection__" GENERIC_ATT2 = "__generic2__" BINDINGS_ATT = "__binding__" class ZuperTypingGlobals: enable_type_checking_difficult: ClassVar[bool] = True enable_type_checking = True cache_enabled = True monkey_patch_Generic = False monkey_patch_dataclass = False class MakeTypeCache: cache = {} from .logging import logger import os # # vname = "ZUPER_TYPING_PATCH" # if vname in os.environ: # pragma: no cover # logger.info(f"Enabling monkey_patch_Generic because of {vname}") # monkey_patch_Generic = True # else: # pragma: no cover # logger.info(f"Disabling monkey_patch_Generic because of {vname}") # monkey_patch_Generic = False circle_job = os.environ.get("CIRCLE_JOB", None) # logger.info(f"Circle JOB: {circle_job!r}") if circle_job == "test-3.7-no-cache": # pragma: no cover cache_enabled = False logger.warning("Disabling cache (zuper_typing:cache_enabled) due to circle_job.")
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/constants.py
constants.py
from typing import Any, cast, ClassVar, Dict, List, Set, Tuple, Type, TypeVar from zuper_typing.aliases import TypeLike from .annotations_tricks import ( get_Dict_args, get_Dict_name_K_V, get_FixedTupleLike_args, get_List_arg, get_Set_arg, get_Set_name_V, is_Dict, is_FixedTupleLike, is_List, is_Set, name_for_type_like, ) _V = TypeVar("_V") _K = TypeVar("_K") _X = TypeVar("_X") _Y = TypeVar("_Y") _Z = TypeVar("_Z") class CustomSet(set): __set_type__: ClassVar[type] def __hash__(self) -> Any: try: return self._cached_hash except AttributeError: try: h = self._cached_hash = hash(tuple(sorted(self))) except TypeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomList(list): __list_type__: ClassVar[type] def __hash__(self) -> Any: # pragma: no cover try: return self._cached_hash except AttributeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomTuple(tuple): __tuple_types__: ClassVar[Tuple[type, ...]] def __hash__(self) -> Any: # pragma: no cover try: return self._cached_hash except AttributeError: # pragma: no cover h = self._cached_hash = hash(tuple(self)) return h class CustomDict(dict): __dict_type__: ClassVar[Tuple[type, type]] def __hash__(self) -> Any: try: return self._cached_hash except AttributeError: try: h = self._cached_hash = hash(tuple(sorted(self.items()))) except TypeError: # pragma: no cover h = self._cached_hash = hash(tuple(self.items())) return h def copy(self: _X) -> _X: return type(self)(self) def get_CustomSet_arg(x: Type[CustomSet]) -> TypeLike: assert is_CustomSet(x), x return x.__set_type__ def get_CustomList_arg(x: Type[CustomList]) -> TypeLike: assert is_CustomList(x), x return x.__list_type__ def get_CustomDict_args(x: Type[CustomDict]) -> Tuple[TypeLike, TypeLike]: assert is_CustomDict(x), x return x.__dict_type__ def get_CustomTuple_args(x: Type[CustomTuple]) -> Tuple[TypeLike, ...]: assert is_CustomTuple(x), x return x.__tuple_types__ def is_CustomSet(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomSet) def is_CustomList(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomList) def is_CustomDict(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomDict) def is_CustomTuple(x: TypeLike) -> bool: return isinstance(x, type) and issubclass(x, CustomTuple) def is_SetLike(x: TypeLike) -> bool: return (x is set) or is_Set(x) or is_CustomSet(x) def is_ListLike(x: TypeLike) -> bool: return (x is list) or is_List(x) or is_CustomList(x) def is_DictLike(x: TypeLike) -> bool: return (x is dict) or is_Dict(x) or is_CustomDict(x) def is_ListLike_canonical(x: Type[List]) -> bool: return is_CustomList(x) def is_DictLike_canonical(x: Type[Dict]) -> bool: return is_CustomDict(x) def is_SetLike_canonical(x: Type[Set]) -> bool: return is_CustomSet(x) def get_SetLike_arg(x: Type[Set[_V]]) -> Type[_V]: if x is set: return Any if is_Set(x): return get_Set_arg(x) if is_CustomSet(x): x = cast(Type[CustomSet], x) return get_CustomSet_arg(x) assert False, x def get_ListLike_arg(x: Type[List[_V]]) -> Type[_V]: if x is list: return Any if is_List(x): return get_List_arg(x) if is_CustomList(x): # noinspection PyTypeChecker return get_CustomList_arg(x) assert False, x def get_DictLike_args(x: Type[Dict[_K, _V]]) -> Tuple[Type[_K], Type[_V]]: assert is_DictLike(x), x if is_Dict(x): return get_Dict_args(x) elif is_CustomDict(x): x = cast(Type[CustomDict], x) return get_CustomDict_args(x) elif x is dict: return Any, Any else: assert False, x def get_DictLike_name(T: Type[Dict]) -> str: assert is_DictLike(T) K, V = get_DictLike_args(T) return get_Dict_name_K_V(K, V) def get_ListLike_name(x: Type[List]) -> str: V = get_ListLike_arg(x) return "List[%s]" % name_for_type_like(V) def get_SetLike_name(x: Type[Set]) -> str: v = get_SetLike_arg(x) return "Set[%s]" % name_for_type_like(v) Q_ = TypeVar("Q_") K_ = TypeVar("K_") V_ = TypeVar("V_") class Caches: use_cache = True make_set_cache: Dict[Type[Q_], Type[CustomSet]] = {} make_list_cache: Dict[Type[Q_], Type[CustomList]] = {} make_dict_cache: Dict[Tuple[Type[K_], Type[V_]], Type[CustomDict]] = {} make_tuple_cache: Dict[Tuple[TypeLike, ...], Type[CustomTuple]] = {} def assert_good_typelike(x: TypeLike) -> None: if isinstance(x, type): return # if is_dataclass(type(x)): # n = type(x).__name__ # if n in ["Constant"]: # raise AssertionError(x) def make_list(V_: Type[_X]) -> Type[List[Type[_X]]]: if Caches.use_cache: if V_ in Caches.make_list_cache: return Caches.make_list_cache[V_] assert_good_typelike(V_) class MyType(type): def __eq__(self, other) -> bool: V2 = getattr(self, "__list_type__") if is_List(other): return V2 == get_List_arg(other) res2 = ( isinstance(other, type) and issubclass(other, CustomList) and other.__list_type__ == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') def copy(self: _X) -> _X: return type(self)(self) attrs = {"__list_type__": V_, "copy": copy} # name = get_List_name(V) name = "List[%s]" % name_for_type_like(V_) res = MyType(name, (CustomList,), attrs) setattr(res, "EMPTY", res([])) Caches.make_list_cache[V_] = res # noinspection PyTypeChecker return res def make_CustomTuple(Vs: Tuple[TypeLike, ...]) -> Type[Tuple]: if Caches.use_cache: if Vs in Caches.make_tuple_cache: return Caches.make_tuple_cache[Vs] for _ in Vs: assert_good_typelike(_) ATT_TUPLE_TYPES = "__tuple_types__" class MyTupleType(type): def __eq__(self, other) -> bool: V2 = getattr(self, ATT_TUPLE_TYPES) if is_FixedTupleLike(other): return V2 == get_FixedTupleLike_args(other) res2 = ( isinstance(other, type) and issubclass(other, CustomTuple) and getattr(other, ATT_TUPLE_TYPES) == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') def copy(self: _X) -> _X: return type(self)(self) attrs = {ATT_TUPLE_TYPES: Vs, "copy": copy} # name = get_List_name(V) s = ",".join(name_for_type_like(_) for _ in Vs) name = "Tuple[%s]" % s res = MyTupleType(name, (CustomTuple,), attrs) # setattr(res, "EMPTY", res()) Caches.make_tuple_cache[V_] = res # noinspection PyTypeChecker return res def make_set(V: TypeLike) -> Type[CustomSet]: if Caches.use_cache: if V in Caches.make_set_cache: return Caches.make_set_cache[V] assert_good_typelike(V) class MyType(type): def __eq__(self, other) -> bool: V2 = getattr(self, "__set_type__") if is_Set(other): return V2 == get_Set_arg(other) res2 = ( isinstance(other, type) and issubclass(other, CustomSet) and other.__set_type__ == V2 ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX def copy(self: _X) -> _X: return type(self)(self) attrs = {"__set_type__": V, "copy": copy} name = get_Set_name_V(V) res = MyType(name, (CustomSet,), attrs) setattr(res, "EMPTY", res([])) Caches.make_set_cache[V] = res # noinspection PyTypeChecker return res # from . import logger # def make_dict(K: Type[X], V: Type[Y]) -> Type[Dict[Type[X], Type[Y]]]: def make_dict(K: TypeLike, V: TypeLike) -> type: # Type[CustomDict]: key = (K, V) if Caches.use_cache: if key in Caches.make_dict_cache: return Caches.make_dict_cache[key] assert_good_typelike(K) assert_good_typelike(V) class MyType(type): def __eq__(self, other) -> bool: K2, V2 = getattr(self, "__dict_type__") if is_Dict(other): K1, V1 = get_Dict_args(other) return K2 == K1 and V2 == V1 res2 = ( isinstance(other, type) and issubclass(other, CustomDict) and other.__dict_type__ == (K2, V2) ) return res2 def __hash__(cls) -> Any: # pragma: no cover return 1 # XXX if isinstance(V, str): # pragma: no cover msg = f"Trying to make dict with K = {K!r} and V = {V!r}; I need types, not strings." raise ValueError(msg) # warnings.warn('Creating dict', stacklevel=2) attrs = {"__dict_type__": (K, V)} name = get_Dict_name_K_V(K, V) res = MyType(name, (CustomDict,), attrs) setattr(res, "EMPTY", res({})) Caches.make_dict_cache[key] = res # noinspection PyUnresolvedReferences import zuper_typing.my_dict zuper_typing.my_dict.__dict__[res.__name__] = res # noinspection PyTypeChecker return res
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/my_dict.py
my_dict.py
from dataclasses import dataclass, field, is_dataclass from decimal import Decimal from typing import Any, cast, Dict, Iterable, List, Optional, Set, Tuple, Type, Sequence from zuper_commons.text import indent from zuper_typing.aliases import TypeLike from zuper_typing.literal import get_Literal_args, is_Literal from zuper_typing.type_algebra import Matches from zuper_typing.uninhabited import is_Uninhabited from .annotations_tricks import ( get_ForwardRef_arg, get_Iterable_arg, get_NewType_arg, get_Optional_arg, get_Sequence_arg, get_tuple_types, get_TypeVar_name, get_Union_args, is_Any, is_Callable, is_ForwardRef, is_Iterable, is_List, is_Optional, is_Sequence, is_Tuple, is_TypeVar, is_Union, is_ClassVar, ) from .constants import ANNOTATIONS_ATT, BINDINGS_ATT from .my_dict import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, ) from .my_intersection import is_Intersection, get_Intersection_args @dataclass class CanBeUsed: result: bool why: str M: Matches matches: Optional[Dict[str, type]] = None reasons: "Dict[str, CanBeUsed]" = field(default_factory=dict) def __post_init__(self): assert isinstance(self.M, Matches), self self.matches = self.M.get_matches() def __bool__(self): return self.result verbose = False can_be_used_cache = {} def can_be_used_as2( T1: TypeLike, T2: TypeLike, matches: Optional[Matches] = None, assumptions0: Tuple[Tuple[Any, Any], ...] = (), ) -> CanBeUsed: if matches is None: matches = Matches() if is_Any(T2): return CanBeUsed(True, "Any", matches) if is_Any(T1): return CanBeUsed(True, "Any", matches) if is_Uninhabited(T1): return CanBeUsed(True, "Empty", matches) assert isinstance(matches, Matches), matches if (T1, T2) in assumptions0: return CanBeUsed(True, "By assumption", matches) if (T1 is T2) or (T1 == T2): return CanBeUsed(True, "equal", matches) if is_Any(T1) or is_Any(T2): return CanBeUsed(True, "Any ignores everything", matches) if T2 is object: return CanBeUsed(True, "object is the top", matches) # cop out for the easy cases if is_Literal(T1): v1 = get_Literal_args(T1) if is_Literal(T2): v2 = get_Literal_args(T2) included = all(any(x1 == x2 for x2 in v2) for x1 in v1) if included: return CanBeUsed(True, "included", matches) else: return CanBeUsed(False, "not included", matches) raise NotImplementedError((T1, T2)) assumptions = assumptions0 + ((T1, T2),) # logger.info(f'can_be_used_as\n {T1} {T2}\n {assumptions0}') if T1 is type(None): if is_Optional(T2): return CanBeUsed(True, "", matches) elif T2 is type(None): return CanBeUsed(True, "", matches) else: msg = f"Needs type(None), got {T2}" return CanBeUsed(False, msg, matches) if is_Union(T1): if is_Union(T2): if get_Union_args(T1) == get_Union_args(T2): return CanBeUsed(True, "same", matches) # can_be_used(Union[A,B], C) # == can_be_used(A,C) and can_be_used(B,C) for t in get_Union_args(T1): can = can_be_used_as2(t, T2, matches, assumptions) # logger.info(f'can_be_used_as t = {t} {T2}') if not can.result: msg = f"Cannot match {t}" return CanBeUsed(False, msg, matches) return CanBeUsed(True, "", matches) if is_Union(T2): reasons = [] for t in get_Union_args(T2): can = can_be_used_as2(T1, t, matches, assumptions) if can.result: return CanBeUsed(True, f"union match with {t} ", can.M) reasons.append(f"- {t}: {can.why}") msg = f"Cannot use {T1} as any of {T2}:\n" + "\n".join(reasons) return CanBeUsed(False, msg, matches) if is_TypeVar(T2): n2 = get_TypeVar_name(T2) if is_TypeVar(T1): n1 = get_TypeVar_name(T1) if n1 == n2: # TODO: intersection of bounds return CanBeUsed(True, "", matches) else: matches = matches.must_be_subtype_of(n1, T2) # raise NotImplementedError((T1, T2)) matches = matches.must_be_supertype_of(n2, T1) return CanBeUsed(True, "", matches) # # if T2.__name__ not in matches: # matches = dict(matches) # matches[T2.__name__] = T1 # return CanBeUsed(True, "", matches) # else: # prev = matches[T2.__name__] # if prev == T1: # return CanBeUsed(True, "", matches) # else: # raise NotImplementedError((T1, T2, matches)) if is_Intersection(T1): if is_Intersection(T2): if get_Intersection_args(T1) == get_Intersection_args(T2): return CanBeUsed(True, "same", matches) # Int[a, b] <= Int[C, D] # = Int[a, b] <= C Int[a, b] <= D for t2 in get_Intersection_args(T2): can = can_be_used_as2(T1, t2, matches, assumptions) # logger.info(f'can_be_used_as t = {t} {T2}') if not can.result: msg = f"Cannot match {t2}" return CanBeUsed(False, msg, matches) return CanBeUsed(True, "", matches) if is_Intersection(T2): # a <= Int[C, D] # = a <= C and a <= D reasons = [] for t2 in get_Intersection_args(T2): can = can_be_used_as2(T1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"no match {T1} {t2} ", can.M) msg = f"Cannot use {T1} as any of {T2}:\n" + "\n".join(reasons) return CanBeUsed(False, msg, matches) if is_TypeVar(T1): n1 = get_TypeVar_name(T1) matches = matches.must_be_subtype_of(n1, T2) return CanBeUsed(True, "Any", matches) # TODO: not implemented if is_Optional(T1): t1 = get_Optional_arg(T1) if is_Optional(T2): t2 = get_Optional_arg(T2) return can_be_used_as2(t1, t2, matches, assumptions) if T2 is type(None): return CanBeUsed(True, "", matches) return can_be_used_as2(t1, T2, matches, assumptions) if is_Optional(T2): t2 = get_Optional_arg(T2) if is_Optional(T1): t1 = get_Optional_arg(T1) return can_be_used_as2(t1, t2, matches, assumptions) return can_be_used_as2(T1, t2, matches, assumptions) if is_DictLike(T2): if not is_DictLike(T1): msg = f"Expecting a dictionary, got {T1}" return CanBeUsed(False, msg, matches) else: K1, V1 = get_DictLike_args(T1) K2, V2 = get_DictLike_args(T2) rk = can_be_used_as2(K1, K2, matches, assumptions) if not rk: return CanBeUsed(False, f"keys {K1} {K2}: {rk}", matches) rv = can_be_used_as2(V1, V2, rk.M, assumptions) if not rv: return CanBeUsed(False, f"values {V1} {V2}: {rv}", matches) return CanBeUsed(True, f"ok: {rk} {rv}", rv.M) else: if is_DictLike(T1): msg = "A Dict needs a dictionary" return CanBeUsed(False, msg, matches) assert not is_Union(T2) if is_dataclass(T2): # try: # if issubclass(T1, T2): # return True, '' # except: # pass if ( hasattr(T1, "__name__") and T1.__name__.startswith("Loadable") and hasattr(T1, BINDINGS_ATT) ): T1 = list(getattr(T1, BINDINGS_ATT).values())[0] if not is_dataclass(T1): if verbose: msg = ( f"Expecting dataclass to match to {T2}, got something that is not a " f"dataclass: {T1}" ) msg += f" union: {is_Union(T1)}" else: msg = "not dataclass" return CanBeUsed(False, msg, matches) # h1 = get_type_hints(T1) # h2 = get_type_hints(T2) key = (T1.__module__, T1.__qualname__, T2.__module__, T2.__qualname__) if key in can_be_used_cache: return can_be_used_cache[key] h1 = getattr(T1, ANNOTATIONS_ATT, {}) h2 = getattr(T2, ANNOTATIONS_ATT, {}) for k, v2 in h2.items(): if not k in h1: if verbose: msg = ( f'Type {T2}\n requires field "{k}" \n of type {v2} \n but {T1} does ' f"" f"not have it. " ) else: msg = k res = CanBeUsed(False, msg, matches) can_be_used_cache[key] = res return res v1 = h1[k] # XXX if is_ClassVar(v1): continue can = can_be_used_as2(v1, v2, matches, assumptions) if not can.result: if verbose: msg = ( f'Type {T2}\n requires field "{k}"\n of type\n {v2} \n but' + f" {T1}\n has annotated it as\n {v1}\n which cannot be used. " ) msg += "\n\n" + f"assumption: {assumptions}" msg += "\n\n" + indent(can.why, "> ") else: msg = "" res = CanBeUsed(False, msg, matches) can_be_used_cache[key] = res return res res = CanBeUsed(True, "dataclass", matches) can_be_used_cache[key] = res return res if T1 is int: if T2 is int: return CanBeUsed(True, "", matches) else: msg = "Need int" return CanBeUsed(False, msg, matches) if T1 is str: assert T2 is not str msg = "A string can only be used a string" return CanBeUsed(False, msg, matches) if is_Tuple(T1): assert not is_Union(T2) if not is_Tuple(T2): msg = "A tuple can only be used as a tuple" return CanBeUsed(False, msg, matches) else: T1 = cast(Type[Tuple], T1) T2 = cast(Type[Tuple], T2) for t1, t2 in zip(get_tuple_types(T1), get_tuple_types(T2)): can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) matches = can.M return CanBeUsed(True, "", matches) if is_Tuple(T2): assert not is_Tuple(T1) return CanBeUsed(False, "", matches) if is_Any(T1): assert not is_Union(T2) if not is_Any(T2): msg = "Any is the top" return CanBeUsed(False, msg, matches) if is_ListLike(T2): if not is_ListLike(T1): msg = "A List can only be used as a List" return CanBeUsed(False, msg, matches) T1 = cast(Type[List], T1) T2 = cast(Type[List], T2) t1 = get_ListLike_arg(T1) t2 = get_ListLike_arg(T2) # print(f'matching List with {t1} {t2}') can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) return CanBeUsed(True, "", can.M) if is_Callable(T2): if not is_Callable(T1): return CanBeUsed(False, "not callable", matches) raise NotImplementedError((T1, T2)) if is_ForwardRef(T1): n1 = get_ForwardRef_arg(T1) if is_ForwardRef(T2): n2 = get_ForwardRef_arg(T2) if n1 == n2: return CanBeUsed(True, "", matches) else: return CanBeUsed(False, "different name", matches) else: return CanBeUsed(False, "not fw ref", matches) if is_ForwardRef(T2): n2 = get_ForwardRef_arg(T2) if hasattr(T1, "__name__"): if T1.__name__ == n2: return CanBeUsed(True, "", matches) else: return CanBeUsed(False, "different name", matches) if is_Iterable(T2): T2 = cast(Type[Iterable], T2) t2 = get_Iterable_arg(T2) if is_Iterable(T1): T1 = cast(Type[Iterable], T1) t1 = get_Iterable_arg(T1) return can_be_used_as2(t1, t2, matches) if is_SetLike(T1): T1 = cast(Type[Set], T1) t1 = get_SetLike_arg(T1) return can_be_used_as2(t1, t2, matches) if is_ListLike(T1): T1 = cast(Type[List], T1) t1 = get_ListLike_arg(T1) return can_be_used_as2(t1, t2, matches) if is_DictLike(T1): T1 = cast(Type[Dict], T1) K, V = get_DictLike_args(T1) t1 = Tuple[K, V] return can_be_used_as2(t1, t2, matches) return CanBeUsed(False, "expect iterable", matches) if is_SetLike(T2): if not is_SetLike(T1): msg = "A Set can only be used as a Set" return CanBeUsed(False, msg, matches) t1 = get_SetLike_arg(T1) t2 = get_SetLike_arg(T2) # print(f'matching List with {t1} {t2}') can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed( False, f"Set argument fails", matches, reasons={"set_arg": can} ) return CanBeUsed(True, "", can.M) if is_Sequence(T1): T1 = cast(Type[Sequence], T1) t1 = get_Sequence_arg(T1) if is_ListLike(T2): T2 = cast(Type[List], T2) t2 = get_ListLike_arg(T2) can = can_be_used_as2(t1, t2, matches, assumptions) if not can.result: return CanBeUsed(False, f"{t1} {T2}", matches) return CanBeUsed(True, "", can.M) msg = f"Needs a Sequence[{t1}], got {T2}" return CanBeUsed(False, msg, matches) if isinstance(T1, type) and isinstance(T2, type): # NOTE: issubclass(A, B) == type(T2).__subclasscheck__(T2, T1) if type.__subclasscheck__(T2, T1): return CanBeUsed(True, f"type.__subclasscheck__ {T1} {T2}", matches) else: msg = f"Type {T1} ({id(T1)}) \n is not a subclass of {T2} ({id(T2)}) " msg += f"\n is : {T1 is T2}" return CanBeUsed(False, msg, matches) if is_List(T1): msg = f"Needs a List, got {T2}" return CanBeUsed(False, msg, matches) if T2 is type(None): msg = f"Needs type(None), got {T1}" return CanBeUsed(False, msg, matches) trivial = (int, str, bool, Decimal, datetime, float) if T2 in trivial: if T1 in trivial: raise NotImplementedError((T1, T2)) return CanBeUsed(False, "", matches) from .annotations_tricks import is_NewType if is_NewType(T1): n1 = get_NewType_arg(T1) if is_NewType(T2): n2 = get_NewType_arg(T2) if n1 == n2: return CanBeUsed(True, "", matches) else: raise NotImplementedError((T1, T2)) else: raise NotImplementedError((T1, T2)) # msg = f"{T1} ? {T2}" # pragma: no cover raise NotImplementedError((T1, T2)) from datetime import datetime
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/subcheck.py
subcheck.py
import inspect import os from typing import Optional from zuper_commons.text import indent from zuper_typing.debug_print_ import debug_print from zuper_typing.logging import logger def ztinfo(msg: Optional[str] = None, **kwargs): curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) frame, filename, line, fname, *rest = calframe[1] fn = os.path.basename(filename) if msg is None: msg = "" m = str(msg) for k, v in kwargs.items(): m += "\n" + indent(debug_print(v), "│ ", k + ": ") logger.info(f"{fn}:{line}|" + fname + "()|" + "\n" + m)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/logging_util.py
logging_util.py
from dataclasses import dataclass, fields, is_dataclass from datetime import datetime from decimal import Decimal from typing import cast, Dict, Iterator, List, Optional, Set, Tuple, Type, Union from .aliases import TypeLike from .annotations_tricks import ( get_ClassVar_arg, get_fields_including_static, get_FixedTupleLike_args, get_NewType_arg, get_NewType_name, get_Optional_arg, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_ClassVar, is_FixedTupleLike, is_NewType, is_Optional, is_Type, is_TypeLike, is_TypeVar, is_Union, is_VarTuple, ) from .exceptions import ZValueError from .my_dict import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, ) from .my_intersection import get_Intersection_args, is_Intersection from .uninhabited import is_Uninhabited @dataclass class Patch: __print_order = ["prefix_str", "value1", "value2"] prefix: Tuple[Union[str, int], ...] value1: object value2: Optional[object] prefix_str: Optional[str] = None def __post_init__(self): self.prefix_str = "/".join(map(str, self.prefix)) def assert_equivalent_objects(ob1: object, ob2: object): if is_TypeLike(ob1): ob1 = cast(TypeLike, ob1) ob2 = cast(TypeLike, ob2) assert_equivalent_types(ob1, ob2) else: patches = get_patches(ob1, ob2) if patches: msg = "The objects are not equivalent" raise ZValueError(msg, ob1=ob1, ob2=ob2, patches=patches) def get_patches(a: object, b: object) -> List[Patch]: patches = list(patch(a, b, ())) return patches def get_fields_values(x: dataclass) -> Dict[str, object]: res = {} for f in fields(type(x)): k = f.name v0 = getattr(x, k) res[k] = v0 return res def is_dataclass_instance(x: object) -> bool: return not isinstance(x, type) and is_dataclass(x) import numpy as np def patch(o1, o2, prefix: Tuple[Union[str, int], ...]) -> Iterator[Patch]: if isinstance(o1, np.ndarray): if np.all(o1 == o2): return else: yield Patch(prefix, o1, o2) if o1 == o2: return if is_TypeLike(o1) and is_TypeLike(o2): try: assert_equivalent_types(o1, o2) except NotEquivalentException: yield Patch(prefix, o1, o2) elif is_dataclass_instance(o1) and is_dataclass_instance(o2): fields1 = get_fields_values(o1) fields2 = get_fields_values(o2) if list(fields1) != list(fields2): yield Patch(prefix, o1, o2) for k in fields1: v1 = fields1[k] v2 = fields2[k] yield from patch(v1, v2, prefix + (k,)) elif isinstance(o1, dict) and isinstance(o2, dict): for k, v in o1.items(): if not k in o2: yield Patch(prefix + (k,), v, None) else: yield from patch(v, o2[k], prefix + (k,)) elif isinstance(o1, list) and isinstance(o2, list): for i, v in enumerate(o1): if i >= len(o2) - 1: yield Patch(prefix + (i,), v, None) else: yield from patch(o1[i], o2[i], prefix + (i,)) else: if o1 != o2: yield Patch(prefix, o1, o2) class NotEquivalentException(ZValueError): pass def assert_equivalent_types(T1: TypeLike, T2: TypeLike, assume_yes: set = None): if assume_yes is None: assume_yes = set() # debug(f'equivalent', T1=T1, T2=T2) key = (id(T1), id(T2)) if key in assume_yes: return assume_yes = set(assume_yes) assume_yes.add(key) try: # print(f'assert_equivalent_types({T1},{T2})') if T1 is T2: # logger.debug('same by equality') return # if hasattr(T1, '__dict__'): # debug('comparing', # T1=f'{T1!r}', # T2=f'{T2!r}', # T1_dict=T1.__dict__, T2_dict=T2.__dict__) # for these builtin we cannot set/get the attrs # if not isinstance(T1, typing.TypeVar) and (not isinstance(T1, ForwardRef)) and not is_Dict(T1): if is_dataclass(T1): if not is_dataclass(T2): raise NotEquivalentException(T1=T1, T2=T2) for k in ["__name__", "__module__", "__doc__"]: msg = f"Difference for {k} of {T1} ({type(T1)}) and {T2} ({type(T2)}" v1 = getattr(T1, k, ()) v2 = getattr(T2, k, ()) if v1 != v2: raise NotEquivalentException(msg, v1=v1, v2=v2) # assert_equal(, , msg=msg) fields1 = get_fields_including_static(T1) fields2 = get_fields_including_static(T2) if list(fields1) != list(fields2): msg = f"Different fields" raise NotEquivalentException(msg, fields1=fields1, fields2=fields2) ann1 = getattr(T1, "__annotations__", {}) ann2 = getattr(T2, "__annotations__", {}) # redundant with above # if list(ann1) != list(ann2): # msg = f'Different fields: {list(fields1)} != {list(fields2)}' # raise NotEquivalent(msg) for k in fields1: t1 = fields1[k].type t2 = fields2[k].type # debug( # f"checking the fields {k}", # t1=f"{t1!r}", # t2=f"{t2!r}", # t1_ann=f"{T1.__annotations__[k]!r}", # t2_ann=f"{T2.__annotations__[k]!r}", # ) try: assert_equivalent_types(t1, t2, assume_yes=assume_yes) except NotEquivalentException as e: msg = f"Could not establish the annotation {k!r} to be equivalent" raise NotEquivalentException( msg, t1=t1, t2=t2, t1_ann=T1.__annotations__[k], t2_ann=T2.__annotations__[k], t1_att=getattr(T1, k, "no attribute"), t2_att=getattr(T2, k, "no attribute"), ) from e d1 = fields1[k].default d2 = fields2[k].default try: assert_equivalent_objects(d1, d2) except ZValueError as e: raise NotEquivalentException(d1=d1, d2=d2) from e # if d1 != d2: # msg = f"Defaults for {k!r} are different." # raise NotEquivalentException(msg, d1=d1, d2=d2) # # d1 = fields1[k].default_factory # d2 = fields2[k].default # if d1 != d2: # msg = f"Defaults for {k!r} are different." # raise NotEquivalentException(msg, d1=d1, d2=d2) for k in ann1: t1 = ann1[k] t2 = ann2[k] try: assert_equivalent_types(t1, t2, assume_yes=assume_yes) except NotEquivalentException as e: msg = f"Could not establish the annotation {k!r} to be equivalent" raise NotEquivalentException( msg, t1=t1, t2=t2, t1_ann=T1.__annotations__[k], t2_ann=T2.__annotations__[k], t1_att=getattr(T1, k, "no attribute"), t2_att=getattr(T2, k, "no attribute"), ) from e # for k in ['__annotations__']: # assert_equivalent_types(getattr(T1, k, None), getattr(T2, k, None)) # if False: # if hasattr(T1, 'mro'): # if len(T1.mro()) != len(T2.mro()): # msg = pretty_dict('Different mros', dict(T1=T1.mro(), T2=T2.mro())) # raise AssertionError(msg) # # for m1, m2 in zip(T1.mro(), T2.mro()): # if m1 is T1 or m2 is T2: continue # assert_equivalent_types(m1, m2, assume_yes=set()) elif is_ClassVar(T1): if not is_ClassVar(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_ClassVar_arg(T1) t2 = get_ClassVar_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_Optional(T1): if not is_Optional(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_Optional_arg(T1) t2 = get_Optional_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_Union(T1): if not is_Union(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_Union_args(T1) ts2 = get_Union_args(T2) for t1, t2 in zip(ts1, ts2): assert_equivalent_types(t1, t2, assume_yes) elif is_Intersection(T1): if not is_Intersection(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_Intersection_args(T1) ts2 = get_Intersection_args(T2) for t1, t2 in zip(ts1, ts2): assert_equivalent_types(t1, t2, assume_yes) elif is_FixedTupleLike(T1): if not is_FixedTupleLike(T2): raise NotEquivalentException(T1=T1, T2=T2) ts1 = get_FixedTupleLike_args(T1) ts2 = get_FixedTupleLike_args(T2) for t1, t2 in zip(ts1, ts2): assert_equivalent_types(t1, t2, assume_yes) elif is_VarTuple(T1): if not is_VarTuple(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_VarTuple_arg(T1) t2 = get_VarTuple_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_SetLike(T1): T1 = cast(Type[Set], T1) if not is_SetLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[Set], T2) t1 = get_SetLike_arg(T1) t2 = get_SetLike_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_ListLike(T1): T1 = cast(Type[List], T1) if not is_ListLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[List], T2) t1 = get_ListLike_arg(T1) t2 = get_ListLike_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_DictLike(T1): T1 = cast(Type[Dict], T1) if not is_DictLike(T2): raise NotEquivalentException(T1=T1, T2=T2) T2 = cast(Type[Dict], T2) t1, u1 = get_DictLike_args(T1) t2, u2 = get_DictLike_args(T2) assert_equivalent_types(t1, t2, assume_yes) assert_equivalent_types(u1, u2, assume_yes) elif is_Any(T1): if not is_Any(T2): raise NotEquivalentException(T1=T1, T2=T2) elif is_TypeVar(T1): if not is_TypeVar(T2): raise NotEquivalentException(T1=T1, T2=T2) n1 = get_TypeVar_name(T1) n2 = get_TypeVar_name(T2) if n1 != n2: raise NotEquivalentException(n1=n1, n2=n2) elif T1 in (int, str, bool, Decimal, datetime, float, type): if T1 != T2: raise NotEquivalentException(T1=T1, T2=T2) elif is_NewType(T1): if not is_NewType(T2): raise NotEquivalentException(T1=T1, T2=T2) n1 = get_NewType_name(T1) n2 = get_NewType_name(T2) if n1 != n2: raise NotEquivalentException(T1=T1, T2=T2) o1 = get_NewType_arg(T1) o2 = get_NewType_arg(T2) assert_equivalent_types(o1, o2, assume_yes) elif is_Type(T1): if not is_Type(T2): raise NotEquivalentException(T1=T1, T2=T2) t1 = get_Type_arg(T1) t2 = get_Type_arg(T2) assert_equivalent_types(t1, t2, assume_yes) elif is_Uninhabited(T1): if not is_Uninhabited(T2): raise NotEquivalentException(T1=T1, T2=T2) else: raise NotImplementedError((T1, T2)) except NotEquivalentException as e: # logger.error(e) msg = f"Could not establish the two types to be equivalent." raise NotEquivalentException(msg, T1=T1, T2=T2) from e # assert T1 == T2 # assert_equal(T1.mro(), T2.mro())
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/get_patches_.py
get_patches_.py
from dataclasses import dataclass, field, Field, fields, is_dataclass, MISSING, replace from datetime import datetime from decimal import Decimal from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Type, TypeVar import termcolor from frozendict import frozendict from zuper_commons.text import indent from zuper_commons.text.coloring import get_length_on_screen, remove_escapes from zuper_commons.text.table import format_table, Style from zuper_commons.types.exceptions import ZException from zuper_commons.ui.colors import ( color_constant, color_float, color_int, color_ops, color_par, color_synthetic_types, color_typename, color_typename2, colorize_rgb, ) from .aliases import TypeLike from .annotations_tricks import ( get_Callable_info, get_ClassVar_arg, get_fields_including_static, get_FixedTupleLike_args, get_Optional_arg, get_Type_arg, get_TypeVar_bound, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_Dict, is_FixedTupleLike, is_ForwardRef, is_Iterable, is_Iterator, is_List, is_NewType, is_Optional, is_Sequence, is_Set, is_Type, is_TypeLike, is_TypeVar, is_Union, is_VarTuple, name_for_type_like, ) from .monkey_patching_typing import ( DataclassHooks, debug_print_bytes, debug_print_date, debug_print_str, ) from .my_dict import ( CustomDict, CustomList, CustomSet, get_CustomDict_args, get_CustomList_arg, get_CustomSet_arg, is_CustomDict, is_CustomList, is_CustomSet, ) from .my_intersection import get_Intersection_args, is_Intersection from .uninhabited import is_Uninhabited __all__ = ["debug_print"] @dataclass class DPOptions: obey_print_order: bool = True do_special_EV: bool = True do_not_display_defaults: bool = True compact: bool = False abbreviate: bool = False # |│┃┆ default_border_left = "│ " # <-- note box-drawing id_gen: Callable[[object], object] = id # cid_if_known max_initial_levels: int = 20 omit_type_if_empty: bool = True omit_type_if_short: bool = True ignores: List[Tuple[str, str]] = field(default_factory=list) other_decoration_dataclass: Callable[[object], str] = lambda _: "" abbreviate_zuper_lang: bool = False ignore_dunder_dunder: bool = False def get_default_dpoptions() -> DPOptions: ignores = [] id_gen = id return DPOptions(ignores=ignores, id_gen=id_gen) def remove_color_if_no_support(f): def f2(*args, **kwargs): s = f(*args, **kwargs) from zuper_commons.types.exceptions import disable_colored if disable_colored(): # pragma: no cover s = remove_escapes(s) return s return f2 @remove_color_if_no_support def debug_print(x: object, opt: Optional[DPOptions] = None) -> str: if opt is None: opt = get_default_dpoptions() max_levels = opt.max_initial_levels already = {} stack = () return debug_print0(x, max_levels=max_levels, already=already, stack=stack, opt=opt) ZException.entries_formatter = debug_print def debug_print0( x: object, *, max_levels: int, already: Dict[int, str], stack: Tuple[int, ...], opt: DPOptions, ) -> str: if id(x) in stack: if hasattr(x, "__name__"): n = x.__name__ return color_typename2(n + "↑") # ↶' return "(recursive)" if opt.compact: if isinstance(x, type) and is_dataclass(x): return color_typename(x.__name__) # logger.info(f'stack: {stack} {id(x)} {type(x)}') stack2 = stack + (id(x),) args = dict(max_levels=max_levels, already=already, stack=stack2, opt=opt) dpa = lambda _: debug_print0(_, **args) opt_compact = replace(opt, compact=True) dp_compact = lambda _: debug_print0( _, max_levels=max_levels, already=already, stack=stack2, opt=opt_compact ) # abbreviate = True if not opt.abbreviate: prefix = "" else: if is_dataclass(x) and type(x).__name__ != "Constant": # noinspection PyBroadException try: h = opt.id_gen(x) except: prefix = termcolor.colored("!!!", "red") # except ValueError: # prefix = '!' else: if h is not None: if h in already: # from . import logger if isinstance(x, type): short = type(x).__name__ + "(...) " else: short = color_typename(type(x).__name__) + "(...) " res = short + termcolor.colored("$" + already[h], "green") # logger.info(f'ok already[h] = {res} already = {already}') return res else: already[h] = f"{len(already)}" prefix = termcolor.colored( "&" + already[h], "green", attrs=["dark"] ) else: prefix = "" else: prefix = "" postfix = " " + prefix if prefix else "" # prefix = prefix + f' L{max_levels}' if isinstance(x, int): return color_int(str(x)) if isinstance(x, float): return color_float(str(x)) if x is type: return color_ops("type") if x is BaseException: return color_ops("BaseException") if x is tuple: return color_ops("tuple") if x is object: return color_ops("object") if x is list: return color_ops("list") if x is dict: return color_ops("dict") if x is type(...): return color_ops("ellipsis") if x is int: return color_ops("int") if x is float: return color_ops("float") if x is bool: return color_ops("bool") if x is str: return color_ops("str") if x is bytes: return color_ops("bytes") if x is set: return color_ops("set") if x is slice: return color_ops("slice") if x is datetime: return color_ops("datetime") if x is Decimal: return color_ops("Decimal") if not isinstance(x, str): if is_TypeLike(x): x = cast(TypeLike, x) return debug_print_typelike(x, dp_compact, dpa, opt, prefix, args) if isinstance(x, bytes): return debug_print_bytes(x) if isinstance(x, str): return debug_print_str(x, prefix=prefix) if isinstance(x, Decimal): return color_ops("Dec") + " " + color_float(str(x)) if isinstance(x, datetime): return debug_print_date(x, prefix=prefix) if isinstance(x, set): return debug_print_set(x, prefix=prefix, **args) if isinstance(x, (dict, frozendict)): return debug_print_dict(x, prefix=prefix, **args) if isinstance(x, tuple): return debug_print_tuple(x, prefix=prefix, **args) if isinstance(x, list): return debug_print_list(x, prefix=prefix, **args) if isinstance(x, (bool, type(None))): return color_ops(str(x)) + postfix if not isinstance(x, type) and is_dataclass(x): return debug_print_dataclass_instance(x, prefix=prefix, **args) if "Expr" in type(x).__name__: return f"{x!r}\n{x}" r = f"instance of {type(x).__name__}:\n{x!r}" # assert not 'typing.Union' in r, (r, x, is_Union(x)) return r cst = color_synthetic_types def debug_print_typelike(x: TypeLike, dp_compact, dpa, opt, prefix, args) -> str: assert is_TypeLike(x), x if is_Any(x): s = name_for_type_like(x) return termcolor.colored(s, on_color="on_magenta") if is_Uninhabited(x): s = "Nothing" return termcolor.colored(s, on_color="on_magenta") if ( (x is type(None)) or is_List(x) or is_Dict(x) or is_Set(x) or is_ClassVar(x) # or is_Type(x) or is_Iterator(x) or is_Sequence(x) or is_Iterable(x) or is_NewType(x) or is_ForwardRef(x) or is_Uninhabited(x) ): return color_ops(name_for_type_like(x)) if is_TypeVar(x): assert isinstance(x, TypeVar), x name = x.__name__ bound = get_TypeVar_bound(x) covariant = getattr(x, "__covariant__") contravariant = getattr(x, "__contravariant__") if covariant: n = name + "+" elif contravariant: n = name + "-" else: n = name + "=" n = cst(n) if bound is not object: n += color_ops("<") + dp_compact(bound) return n if is_CustomDict(x): x = cast(Type[CustomDict], x) K, V = get_CustomDict_args(x) s = cst("Dict") + cst("[") + dp_compact(K) + cst(",") + dp_compact(V) + cst("]") return s if is_Type(x): V = get_Type_arg(x) s = cst("Type") + cst("[") + dp_compact(V) + cst("]") return s if is_ClassVar(x): V = get_ClassVar_arg(x) s = color_ops("ClassVar") + cst("[") + dp_compact(V) + cst("]") return s if is_CustomSet(x): x = cast(Type[CustomSet], x) V = get_CustomSet_arg(x) s = cst("Set") + cst("[") + dp_compact(V) + cst("]") return s if is_CustomList(x): x = cast(Type[CustomList], x) V = get_CustomList_arg(x) s = cst("List") + cst("[") + dp_compact(V) + cst("]") return s if is_Optional(x): V = get_Optional_arg(x) s0 = dp_compact(V) s = color_ops("Optional") + cst("[") + s0 + cst("]") return s if is_FixedTupleLike(x): ts = get_FixedTupleLike_args(x) ss = [] for t in ts: ss.append(dp_compact(t)) args = color_ops(",").join(ss) s = color_ops("Tuple") + cst("[") + args + cst("]") return s if is_VarTuple(x): x = cast(Type[Tuple], x) t = get_VarTuple_arg(x) s = color_ops("Tuple") + cst("[") + dp_compact(t) + ", ..." + cst("]") return s if is_Union(x): Ts = get_Union_args(x) if opt.compact or len(Ts) <= 3: ss = list(dp_compact(v) for v in Ts) inside = color_ops(",").join(ss) s = color_ops("Union") + cst("[") + inside + cst("]") else: ss = list(dpa(v) for v in Ts) s = color_ops("Union") for v in ss: s += "\n" + indent(v, "", color_ops(f"* ")) return s if is_Intersection(x): Ts = get_Intersection_args(x) if opt.compact or len(Ts) <= 3: ss = list(dp_compact(v) for v in Ts) inside = color_ops(",").join(ss) s = color_ops("Intersection") + cst("[") + inside + cst("]") else: ss = list(dpa(v) for v in Ts) s = color_ops("Intersection") for v in ss: s += "\n" + indent(v, "", color_ops(f"* ")) return s if is_Callable(x): info = get_Callable_info(x) def ps(k, v): if k.startswith("__"): return dp_compact(v) else: return f"NamedArg({dp_compact(v)},{k!r})" params = color_ops(",").join( ps(k, v) for k, v in info.parameters_by_name.items() ) ret = dp_compact(info.returns) return ( color_ops("Callable") + cst("[[") + params + color_ops("],") + ret + cst("]") ) if isinstance(x, type) and is_dataclass(x): return debug_print_dataclass_type(x, prefix=prefix, **args) return repr(x) DataclassHooks.dc_str = debug_print def clipped(): return " " + termcolor.colored("...", "blue", on_color="on_yellow") def debug_print_dict( x: dict, *, prefix, max_levels: int, already: Dict, stack: Tuple[int], opt: DPOptions, ): dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) opt_compact = replace(opt, compact=True) dps = lambda _: debug_print0( _, max_levels=max_levels, already={}, stack=stack, opt=opt_compact ) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return color_ops("{}") + ps else: return dps(type(x)) + " " + color_ops("{}") + ps # s = color_ops(type(x).__name__) + postfix s = dps(type(x)) + ps if max_levels == 0: return s + clipped() r = {} for k, v in x.items(): if isinstance(k, str): if k.startswith("zd"): k = "zd..." + k[-4:] k = termcolor.colored(k, "yellow") else: k = dpa(k) # ks = debug_print(k) # if ks.startswith("'"): # ks = k r[k] = dpa(v) ss = [k + ": " + v for k, v in r.items()] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < 50: # x = "," if len(x) == 1 else "" res = color_ops("{") + color_ops(", ").join(ss) + color_ops("}") + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res leftmargin = color_ops(opt.default_border_left) return pretty_dict_compact(s, r, leftmargin=leftmargin, indent_value=0) def debug_print_dataclass_type( x: Type[dataclass], prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions, ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) ps = " " + prefix if prefix else "" # ps += f" {id(x)} {type(x)}" # note breaks string equality if opt.abbreviate_zuper_lang: if x.__module__.startswith("zuper_lang."): return color_constant(x.__name__) more = "" if x.__name__ != x.__qualname__: more += f" ({x.__qualname__})" mod = x.__module__ + "." s = ( color_ops("dataclass") + " " + mod + color_typename(x.__name__) + more + ps ) # + f' {id(x)}' cells = {} # FIXME: what was the unique one ? seen_fields = set() row = 0 all_fields: Dict[str, Field] = get_fields_including_static(x) for name, f in all_fields.items(): T = f.type if opt.ignore_dunder_dunder: if f.name.startswith("__"): continue cells[(row, 0)] = color_ops("field") cells[(row, 1)] = f.name cells[(row, 2)] = color_ops(":") cells[(row, 3)] = dpa(T) if f.default != MISSING: cells[(row, 4)] = color_ops("=") cells[(row, 5)] = dpa(f.default) elif f.default_factory != MISSING: cells[(row, 4)] = color_ops("=") cells[(row, 5)] = f"factory {dpa(f.default_factory)}" if is_ClassVar(T): if not hasattr(T, name): cells[(row, 6)] = "no attribute set" else: v = getattr(T, name) # cells[(row, 4)] = color_ops("=") cells[(row, 6)] = dpa(v) seen_fields.add(f.name) row += 1 # for k, ann in x.__annotations__.items(): # if k in seen_fields: # continue # if not is_ClassVar(ann): # continue # T = get_ClassVar_arg(ann) # # cells[(row, 0)] = color_ops("classvar") # cells[(row, 1)] = k # cells[(row, 2)] = color_ops(':') # cells[(row, 3)] = dpa(T) # # if hasattr(x, k): # cells[(row, 4)] = color_ops('=') # cells[(row, 5)] = dpa(getattr(x, k)) # else: # cells[(row, 5)] = '(no value)' # # row += 1 if not cells: return s + ": (no fields)" align_right = Style(halign="right") col_style = {0: align_right, 1: align_right} res = format_table(cells, style="spaces", draw_grid_v=False, col_style=col_style) return s + "\n" + res # indent(res, ' ') def debug_print_list( x: list, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) dps = lambda _: debug_print0( _, opt=opt, max_levels=max_levels, already={}, stack=stack ) ps = " " + prefix if prefix else "" s = dps(type(x)) + ps if max_levels <= 0: return s + clipped() if len(x) == 0: if opt.omit_type_if_empty: return color_ops("[]") + ps else: return dps(type(x)) + " " + color_ops("[]") + ps ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < 50: # x = "," if len(x) == 1 else "" res = color_ops("[") + color_ops(", ").join(ss) + color_ops("]") + ps return res for i, si in enumerate(ss): # s += '\n' + indent(debug_print(v), '', color_ops(f'#{i} ')) s += "\n" + indent(si, "", color_ops(f"#{i} ")) return s def debug_print_set( x: set, *, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) dps = lambda _: debug_print0( _, max_levels=max_levels, already={}, stack=stack, opt=opt ) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return color_ops("∅") + ps else: return dps(type(x)) + " " + color_ops("∅") + ps s = dps(type(x)) + ps if max_levels <= 0: return s + clipped() ss = [dpa(v) for v in x] nlines = sum(_.count("\n") for _ in ss) tlen = sum(get_length_on_screen(_) for _ in ss) if nlines == 0 and tlen < 50: res = color_ops("{") + color_ops(", ").join(ss) + color_ops("}") + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res for vi in ss: # s += '\n' + indent(debug_print(v), '', color_ops(f'#{i} ')) s += "\n" + indent(dpa(vi), "", color_ops(f"* ")) return s def debug_print_tuple( x: tuple, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions ) -> str: dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) dps = lambda _: debug_print0( _, max_levels=max_levels, already={}, stack=stack, opt=opt ) ps = " " + prefix if prefix else "" if len(x) == 0: if opt.omit_type_if_empty: return color_ops("()") + ps else: return dps(type(x)) + " " + color_ops("()") + ps s = dps(type(x)) + ps if max_levels <= 0: return s + clipped() ss = [dpa(v) for v in x] tlen = sum(get_length_on_screen(_) for _ in ss) nlines = sum(_.count("\n") for _ in ss) if nlines == 0 and tlen < 50: x = "," if len(x) == 1 else "" res = color_ops("(") + color_ops(", ").join(ss) + x + color_ops(")") + ps if opt.omit_type_if_short: return res else: return dps(type(x)) + " " + res for i, si in enumerate(ss): s += "\n" + indent(si, "", color_ops(f"#{i} ")) return s def debug_print_dataclass_instance( x: dataclass, prefix: str, max_levels: int, already: Dict, stack: Tuple, opt: DPOptions, ) -> str: assert is_dataclass(x) fields_x = fields(x) dpa = lambda _: debug_print0( _, max_levels=max_levels - 1, already=already, stack=stack, opt=opt ) # noinspection PyArgumentList other = opt.other_decoration_dataclass(x) CN = type(x).__name__ special_colors = { "EV": "#77aa77", "ZFunction": "#ffffff", "ArgRef": "#00ffff", "ZArg": "#00ffff", "ATypeVar": "#00ffff", "MakeProcedure": "#ffffff", "IF": "#fafaaf", } if CN in special_colors: cn = colorize_rgb(CN, special_colors[CN]) else: cn = color_typename(CN) ps = " " + prefix if prefix else "" s = cn + ps + other if max_levels <= 0: return s + clipped() if opt.obey_print_order and hasattr(x, "__print_order__"): options = x.__print_order__ else: options = [] for f in fields_x: options.append(f.name) if opt.do_not_display_defaults: same = [] for f in fields_x: att = getattr(x, f.name) if f.default != MISSING: if f.default == att: same.append(f.name) elif f.default_factory != MISSING: default = f.default_factory() if default == att: same.append(f.name) to_display = [_ for _ in options if _ not in same] else: to_display = options r = {} dpa_result = {} for k in to_display: # for k, v in x.__annotations__.items(): # v = x.__annotations__[k] if k == "expect": att = getattr(x, k) # logger.info(f'CN {CN} k {k!r} {getattr(att, "val", None)}') if CN == "EV" and k == "expect" and getattr(att, "val", None) is type: expects_type = True continue if not k in to_display: continue if k.startswith("__"): # TODO: make configurable continue if (CN, k) in opt.ignores: continue # r[color_par(k)] = "(non visualized)" else: att = getattr(x, k) r[color_par(k)] = dpa_result[k] = dpa(att) # r[(k)] = debug_print(att) expects_type = False if len(r) == 0: return cn + f"()" + prefix + other if type(x).__name__ == "Constant": s0 = dpa_result["val"] if not "\n" in s0: # 「 」‹ › return color_constant("⟬") + s0 + color_constant("⟭") else: l = color_constant("│ ") # ║") f = color_constant("C ") return indent(s0, l, f) if type(x).__name__ == "QualifiedName": module_name = x.module_name qual_name = x.qual_name return ( color_typename("QN") + " " + module_name + "." + color_typename(qual_name) ) if type(x).__name__ == "ATypeVar": if len(r) == 1: # only if no other stuff return color_synthetic_types(x.typevar_name) if CN == "EV" and opt.do_special_EV: if len(r) == 1: res = list(r.values())[0] else: res = pretty_dict_compact("", r, leftmargin="") if x.pr is not None: color_to_use = x.pr.get_color() else: color_to_use = "#f0f0f0" def colorit(_: str) -> str: return colorize_rgb(_, color_to_use) if expects_type: F = "ET " else: F = "E " l = colorit("┋ ") f = colorit(F) return indent(res, l, f) if len(r) == 1: k0 = list(r)[0] v0 = r[k0] if not "\n" in v0 and not "(" in v0: return cn + f"({k0}={v0.rstrip()})" + prefix + other ss = list(r.values()) tlen = sum(get_length_on_screen(_) for _ in ss) nlines = sum(_.count("\n") for _ in ss) # npars = sum(_.count("(") for _ in ss) if nlines == 0 and tlen < 70: # ok, we can do on one line if type(x).__name__ == "MakeUnion": assert len(r) == 1 ts = x.utypes v = [dpa(_) for _ in ts] return "(" + color_ops(" ∪ ").join(v) + ")" if type(x).__name__ == "MakeIntersection": assert len(r) == 1 ts = x.inttypes v = [dpa(_) for _ in ts] return "(" + color_ops(" ∩ ").join(v) + ")" contents = ", ".join(k + "=" + v for k, v in r.items()) res = cn + "(" + contents + ")" + ps return res if CN == "MakeProcedure": M2 = "┇ " else: M2 = opt.default_border_left if CN in special_colors: leftmargin = colorize_rgb(M2, special_colors[CN]) else: leftmargin = color_typename(M2) return pretty_dict_compact(s, r, leftmargin=leftmargin, indent_value=0) # # def debug_print_dataclass_compact( # x, max_levels: int, already: Dict, stack: Tuple, # opt: DPOptions # ): # dpa = lambda _: debug_print0(_, max_levels=max_levels - 1, already=already, stack=stack, opt=opt) # # dps = lambda _: debug_print(_, max_levels, already={}, stack=stack) # s = color_typename(type(x).__name__) + color_par("(") # ss = [] # for k, v in x.__annotations__.items(): # att = getattr(x, k) # ss.append(f'{color_par(k)}{color_par("=")}{dpa(att)}') # # s += color_par(", ").join(ss) # s += color_par(")") # return s def pretty_dict_compact( head: Optional[str], d: Dict[str, Any], leftmargin="│", indent_value: int = 0 ): # | <-- note box-making if not d: return head + ": (empty dict)" if head else "(empty dict)" s = [] # n = max(get_length_on_screen(str(_)) for _ in d) ordered = list(d) # ks = sorted(d) for k in ordered: v = d[k] heading = str(k) + ":" # if isinstance(v, TypeVar): # # noinspection PyUnresolvedReferences # v = f'TypeVar({v.__name__}, bound={v.__bound__})' # if isinstance(v, dict): # v = pretty_dict_compact("", v) # vs = v if "\n" in v: vs = indent(v, " " * indent_value) s.append(heading) s.append(vs) else: s.append(heading + " " + v) # s.extend(.split('\n')) # return (head + ':\n' if head else '') + indent("\n".join(s), '| ') indented = indent("\n".join(s), leftmargin) return (head + "\n" if head else "") + indented
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/debug_print_.py
debug_print_.py
import dataclasses import typing from datetime import datetime from typing import Dict, Generic, TypeVar import termcolor from zuper_commons.text.boxing import box from zuper_commons.text.text_sidebyside import side_by_side from .constants import ( ANNOTATIONS_ATT, DEPENDS_ATT, monkey_patch_dataclass, monkey_patch_Generic, PYTHON_36, ) from .my_dict import make_dict from .zeneric2 import resolve_types, ZenericFix if PYTHON_36: # pragma: no cover from typing import GenericMeta previous_getitem = GenericMeta.__getitem__ else: from typing import _GenericAlias previous_getitem = _GenericAlias.__getitem__ class Alias1: def __getitem__(self, params): if self is typing.Dict: K, V = params if K is not str: return make_dict(K, V) # noinspection PyArgumentList return previous_getitem(self, params) def original_dict_getitem(a): # noinspection PyArgumentList return previous_getitem(Dict, a) if monkey_patch_Generic: # pragma: no cover if PYTHON_36: # pragma: no cover GenericMeta.__getitem__ = ZenericFix.__getitem__ else: Generic.__class_getitem__ = ZenericFix.__class_getitem__ _GenericAlias.__getitem__ = Alias1.__getitem__ Dict.__getitem__ = Alias1.__getitem__ def _cmp_fn_loose(name, op, self_tuple, other_tuple, *args, **kwargs): body = [ "if other.__class__.__name__ == self.__class__.__name__:", f" return {self_tuple}{op}{other_tuple}", "return NotImplemented", ] fn = dataclasses._create_fn(name, ("self", "other"), body) fn.__doc__ = """ This is a loose comparison function. Instead of comparing: self.__class__ is other.__class__ we compare: self.__class__.__name__ == other.__class__.__name__ """ return fn dataclasses._cmp_fn = _cmp_fn_loose def typevar__repr__(self): if self.__covariant__: prefix = "+" elif self.__contravariant__: prefix = "-" else: prefix = "~" s = prefix + self.__name__ if self.__bound__: if isinstance(self.__bound__, type): b = self.__bound__.__name__ else: b = str(self.__bound__) s += f"<{b}" return s setattr(TypeVar, "__repr__", typevar__repr__) NAME_ARG = "__name_arg__" # need to have this otherwise it's not possible to say that two types are the same class Reg: already = {} def MyNamedArg(T, name: str): try: int(name) except: pass else: msg = f"Tried to create NamedArg with name = {name!r}." raise ValueError(msg) key = f"{T} {name}" if key in Reg.already: return Reg.already[key] class CNamedArg: pass setattr(CNamedArg, NAME_ARG, name) setattr(CNamedArg, "original", T) Reg.already[key] = CNamedArg return CNamedArg import mypy_extensions setattr(mypy_extensions, "NamedArg", MyNamedArg) from dataclasses import dataclass as original_dataclass from typing import Tuple class RegisteredClasses: # klasses: Dict[str, type] = {} klasses: Dict[Tuple[str, str], type] = {} def get_remembered_class(module_name: str, qual_name: str) -> type: k = (module_name, qual_name) return RegisteredClasses.klasses[k] def remember_created_class(res: type, msg: str = ""): k = (res.__module__, res.__qualname__) # logger.info(f"Asked to remember {k}: {msg}") if k in RegisteredClasses.klasses: pass # logger.info(f"Asked to remember again {k}: {msg}") RegisteredClasses.klasses[k] = res # noinspection PyShadowingBuiltins def my_dataclass( _cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, ): def wrap(cls): # logger.info(f'called my_dataclass for {cls} with bases {_cls.__bases__}') # if cls.__name__ == 'B' and len(cls.__bases__) == 1 and cls.__bases__[0].__name__ # == 'object' and len(cls.__annotations__) != 2: # assert False, (cls, cls.__bases__, cls.__annotations__) res = my_dataclass_( cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen, ) # logger.info(f'called my_dataclass for {cls} with bases {_cls.__bases__}, ' # f'returning {res} with bases {res.__bases__} and annotations { # _cls.__annotations__}') remember_created_class(res, "my_dataclass") return res # See if we're being called as @dataclass or @dataclass(). if _cls is None: # We're called with parens. return wrap # We're called as @dataclass without parens. return wrap(_cls) def get_all_annotations(cls: type) -> Dict[str, type]: """ Gets all the annotations including the parents. """ res = {} for base in cls.__bases__: annotations = getattr(base, ANNOTATIONS_ATT, {}) res.update(annotations) # logger.info(f'name {cls.__name__} bases {cls.__bases__} mro {cls.mro()} res {res}') return res # noinspection PyShadowingBuiltins def my_dataclass_( _cls, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False ): original_doc = getattr(_cls, "__doc__", None) # logger.info(_cls.__dict__) unsafe_hash = True if hasattr(_cls, "nominal"): # logger.info('nominal for {_cls}') nominal = True else: nominal = False # # if the class does not have a metaclass, add one # We copy both annotations and constants. This is needed for cases like: # # @dataclass # class C: # a: List[] = field(default_factory=list) # # # if Generic in _cls.__bases__: msg = f"There are problems with initialization: class {_cls.__name__} inherits from Generic: {_cls.__bases__}" raise Exception(msg) if type(_cls) is type: old_annotations = get_all_annotations(_cls) from .zeneric2 import StructuralTyping old_annotations.update(getattr(_cls, ANNOTATIONS_ATT, {})) attrs = {ANNOTATIONS_ATT: old_annotations} for k in old_annotations: if hasattr(_cls, k): attrs[k] = getattr(_cls, k) class Base(metaclass=StructuralTyping): pass _cls2 = type(_cls.__name__, (_cls, Base) + _cls.__bases__, attrs) _cls2.__module__ = _cls.__module__ _cls2.__qualname__ = _cls.__qualname__ _cls = _cls2 else: old_annotations = get_all_annotations(_cls) old_annotations.update(getattr(_cls, ANNOTATIONS_ATT, {})) setattr(_cls, ANNOTATIONS_ATT, old_annotations) k = "__" + _cls.__name__.replace("[", "_").replace("]", "_") if nominal: # # annotations = getattr(K, '__annotations__', {}) old_annotations[k] = bool # typing.Optional[bool] setattr(_cls, k, True) if "__hash__" in _cls.__dict__: unsafe_hash = False # print(_cls.__dict__) # _cls.__dict__['__hash__']= None res = original_dataclass( _cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen, ) # assert dataclasses.is_dataclass(res) refs = getattr(_cls, DEPENDS_ATT, ()) resolve_types(res, refs=refs) def __repr__(self) -> str: return DataclassHooks.dc_repr(self) def __str__(self): return DataclassHooks.dc_str(self) setattr(res, "__repr__", __repr__) setattr(res, "__str__", __str__) setattr(res, "__doc__", original_doc) if nominal: setattr(_cls, k, True) return res def nice_str(self): return DataclassHooks.dc_repr(self) def blue(x): return termcolor.colored(x, "blue") def nice_repr(self): s = termcolor.colored(type(self).__name__, "red") s += blue("(") ss = [] annotations = getattr(type(self), "__annotations__", {}) for k in annotations: a = getattr(self, k) a_s = debug_print_compact(a) eq = blue("=") k = termcolor.colored(k, attrs=["dark"]) ss.append(f"{k}{eq}{a_s}") s += blue(", ").join(ss) s += blue(")") return s def debug_print_compact(x): if isinstance(x, str): return debug_print_str(x, prefix="") if isinstance(x, bytes): return debug_print_bytes(x) if isinstance(x, datetime): return debug_print_date(x, prefix="") return f"{x!r}" def debug_print_str(x: str, *, prefix: str): if type(x) is not str: return type(x).__name__ + " - " + debug_print_str(str(x), prefix=prefix) if x == "\n": return "`\\n`" if x.startswith("Qm"): x2 = "Qm..." + x[-4:] + " " + prefix return termcolor.colored(x2, "magenta") # if x.startswith("zd"): # x2 = "zd..." + x[-4:] + " " + prefix # return termcolor.colored(x2, "magenta") if x.startswith("-----BEGIN"): s = "PEM key" + " " + prefix return termcolor.colored(s, "yellow") if x.startswith("Traceback"): lines = x.split("\n") colored = [termcolor.colored(_, "red") for _ in lines] if colored: colored[0] += " " + prefix s = "\n".join(colored) return s ps = " " + prefix if prefix else "" lines = x.split("\n") if len(lines) > 1: try: res = box(x, color="yellow", attrs=["dark"]) return side_by_side([res, ps]) except: # print(traceback.format_exc()) return "?" if x.startswith("zdpu"): return termcolor.colored(x, "yellow") return "`" + x + "`" + ps # return x.__repr__() + ps def debug_print_date(x: datetime, *, prefix: str): s = x.isoformat()[:19] s = s.replace("T", " ") return termcolor.colored(s, "yellow") + (" " + prefix if prefix else "") def debug_print_bytes(x: bytes): s = f"{len(x)} bytes " + x[:10].__repr__() return termcolor.colored(s, "yellow") class DataclassHooks: dc_repr = nice_repr dc_str = nice_str if monkey_patch_dataclass: setattr(dataclasses, "dataclass", my_dataclass)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/monkey_patching_typing.py
monkey_patching_typing.py
from typing import Tuple, Type from typing_extensions import Literal from zuper_typing.aliases import TypeLike def make_Literal(*values: object) -> TypeLike: # noinspection PyTypeHints return Literal[values] def is_Literal(x: TypeLike) -> bool: return "Literal[" in str(x) def get_Literal_args(x: TypeLike) -> Tuple[object, ...]: assert is_Literal(x) return getattr(x, "__args__")
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/literal.py
literal.py
__version__ = "5.3.0" from .logging import logger logger.info(f"zuper-typing {__version__}") from typing import TYPE_CHECKING if TYPE_CHECKING: # noinspection PyUnresolvedReferences from dataclasses import dataclass # noinspection PyUnresolvedReferences from typing import Generic raise Exception() else: # noinspection PyUnresolvedReferences from .monkey_patching_typing import my_dataclass as dataclass # noinspection PyUnresolvedReferences from .monkey_patching_typing import ZenericFix as Generic from .debug_print_ import debug_print
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/__init__.py
__init__.py
class Unh: def __init__(self): raise Exception() # pragma: no cover def make_Uninhabited(): return Unh def is_Uninhabited(x): return x is Unh
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/uninhabited.py
uninhabited.py
from zuper_commons.types.exceptions import ZException class ZTypeError(ZException, TypeError): pass class ZValueError(ZException, ValueError): pass class ZAssertionError(ZException, AssertionError): pass class ZNotImplementedError(ZException, NotImplementedError): pass
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/exceptions.py
exceptions.py
from dataclasses import dataclass, field, is_dataclass from datetime import datetime from decimal import Decimal from functools import reduce from typing import cast, Dict, List, Optional, Set, Tuple, Type from zuper_typing.aliases import TypeLike from zuper_typing.annotations_tricks import ( get_FixedTupleLike_args, get_Optional_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_FixedTupleLike, is_Optional, is_TypeVar, is_Union, is_VarTuple, make_Tuple, make_Union, make_VarTuple, ) from zuper_typing.exceptions import ZValueError from zuper_typing.my_dict import ( get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_DictLike, is_ListLike, is_SetLike, make_dict, make_list, make_set, ) from zuper_typing.my_intersection import ( get_Intersection_args, is_Intersection, make_Intersection, ) from zuper_typing.uninhabited import is_Uninhabited, make_Uninhabited def unroll_union(a: TypeLike) -> Tuple[TypeLike, ...]: if is_Union(a): return get_Union_args(a) elif is_Optional(a): return (get_Optional_arg(a), type(None)) else: return (a,) def unroll_intersection(a: TypeLike) -> Tuple[TypeLike, ...]: if is_Intersection(a): return get_Intersection_args(a) else: return (a,) def type_sup(a: TypeLike, b: TypeLike) -> TypeLike: assert a is not None assert b is not None assert not isinstance(a, tuple), a assert not isinstance(b, tuple), b if a is b or (a == b): return a if a is object or b is object: return object if is_Uninhabited(a): return b if is_Uninhabited(b): return a if a is type(None): if is_Optional(b): return b else: return Optional[b] if b is type(None): if is_Optional(a): return a else: return Optional[a] if is_Optional(a): return type_sup(type(None), type_sup(get_Optional_arg(a), b)) if is_Optional(b): return type_sup(type(None), type_sup(get_Optional_arg(b), a)) # if is_Union(a) and is_Union(b): # XXX # r = [] # r.extend(unroll_union(a)) # r.extend(unroll_union(b)) # return reduce(type_sup, r) # if is_Union(a) and is_Union(b): ta = unroll_union(a) tb = unroll_union(b) tva, oa = get_typevars(ta) tvb, ob = get_typevars(tb) tv = tuple(set(tva + tvb)) oab = oa + ob if not oab: return make_Union(*tv) else: other = reduce(type_sup, oa + ob) os = unroll_union(other) return make_Union(*(tv + os)) if (a, b) in [(bool, int), (int, bool)]: return int if is_ListLike(a) and is_ListLike(b): a = cast(Type[List], a) b = cast(Type[List], b) A = get_ListLike_arg(a) B = get_ListLike_arg(b) u = type_sup(A, B) return make_list(u) if is_SetLike(a) and is_SetLike(b): a = cast(Type[Set], a) b = cast(Type[Set], b) A = get_SetLike_arg(a) B = get_SetLike_arg(b) u = type_sup(A, B) return make_set(u) if is_DictLike(a) and is_DictLike(b): a = cast(Type[Dict], a) b = cast(Type[Dict], b) KA, VA = get_DictLike_args(a) KB, VB = get_DictLike_args(b) K = type_sup(KA, KB) V = type_sup(VA, VB) return make_dict(K, V) if is_VarTuple(a) and is_VarTuple(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) VA = get_VarTuple_arg(a) VB = get_VarTuple_arg(b) V = type_sup(VA, VB) return make_VarTuple(V) if is_FixedTupleLike(a) and is_FixedTupleLike(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) tas = get_FixedTupleLike_args(a) tbs = get_FixedTupleLike_args(b) ts = tuple(type_sup(ta, tb) for ta, tb in zip(tas, tbs)) return make_Tuple(*ts) if is_dataclass(a) and is_dataclass(b): return type_sup_dataclass(a, b) if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a return make_Union(a, b) # raise NotImplementedError(a, b) def type_inf_dataclass(a: Type[dataclass], b: Type[dataclass]) -> Type[dataclass]: from zuper_typing.monkey_patching_typing import my_dataclass ann_a = a.__annotations__ ann_b = b.__annotations__ all_keys = set(ann_a) | set(ann_b) res = {} for k in all_keys: if k in ann_a and k not in ann_b: R = ann_a[k] elif k not in ann_a and k in ann_b: R = ann_b[k] else: VA = ann_a[k] VB = ann_b[k] R = type_inf(VA, VB) if is_Uninhabited(R): return R res[k] = R name = f"Int_{a.__name__}_{b.__name__}" T2 = my_dataclass( type(name, (), {"__annotations__": res, "__module__": "zuper_typing"}) ) return T2 def type_sup_dataclass(a: Type[dataclass], b: Type[dataclass]) -> Type[dataclass]: from zuper_typing.monkey_patching_typing import my_dataclass ann_a = a.__annotations__ ann_b = b.__annotations__ common_keys = set(ann_a) & set(ann_b) res = {} for k in common_keys: if k in ann_a and k not in ann_b: R = ann_a[k] elif k not in ann_a and k in ann_b: R = ann_b[k] else: VA = ann_a[k] VB = ann_b[k] R = type_sup(VA, VB) res[k] = R name = f"Join_{a.__name__}_{b.__name__}" T2 = my_dataclass( type(name, (), {"__annotations__": res, "__module__": "zuper_typing"}) ) return T2 def type_inf(a: TypeLike, b: TypeLike) -> TypeLike: try: res = type_inf0(a, b) except ZValueError as e: raise raise ZValueError("problem", a=a, b=b) from e if isinstance(res, tuple): raise ZValueError(a=a, b=b, res=res) return res def get_typevars(a: Tuple[TypeLike, ...]) -> Tuple[Tuple, Tuple]: tv = [] ts = [] for _ in a: if is_TypeVar(_): tv.append(_) else: ts.append(_) return tuple(tv), tuple(ts) def type_inf0(a: TypeLike, b: TypeLike) -> TypeLike: assert a is not None assert b is not None if isinstance(a, tuple): raise ZValueError(a=a, b=b) if isinstance(b, tuple): raise ZValueError(a=a, b=b) if a is b or (a == b): return a if a is object: return b if b is object: return a if is_Uninhabited(a): return a if is_Uninhabited(b): return b if is_Optional(a): if b is type(None): return b if is_Optional(b): if a is type(None): return a if is_Optional(a) and is_Optional(b): x = type_inf(get_Optional_arg(a), get_Optional_arg(b)) if is_Uninhabited(x): return type(None) return Optional[x] # if not is_Intersection(a) and is_Intersection(b): # r = (a,) + unroll_intersection(b) # return reduce(type_inf, r) if is_Intersection(a) or is_Intersection(b): ta = unroll_intersection(a) tb = unroll_intersection(b) tva, oa = get_typevars(ta) tvb, ob = get_typevars(tb) tv = tuple(set(tva + tvb)) oab = oa + ob if not oab: return make_Intersection(tv) else: other = reduce(type_inf, oa + ob) os = unroll_intersection(other) return make_Intersection(tv + os) if is_Union(b): # A ^ (C u D) # = A^C u A^D r = [] for t in get_Union_args(b): r.append(type_inf(a, t)) return reduce(type_sup, r) # if is_Intersection(a) and not is_Intersection(b): # res = [] # for aa in get_Intersection_args(a): # r = type_inf(aa) # r.extend(unroll_intersection(a)) # r.extend(unroll_intersection(b)) # put first! # return reduce(type_inf, r) if (a, b) in [(bool, int), (int, bool)]: return bool if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a if is_TypeVar(a) or is_TypeVar(b): return make_Intersection((a, b)) primitive = (bool, int, str, Decimal, datetime, float, bytes, type(None)) if a in primitive or b in primitive: return make_Uninhabited() if is_ListLike(a) ^ is_ListLike(b): return make_Uninhabited() if is_ListLike(a) & is_ListLike(b): a = cast(Type[List], a) b = cast(Type[List], b) A = get_ListLike_arg(a) B = get_ListLike_arg(b) u = type_inf(A, B) return make_list(u) if is_SetLike(a) ^ is_SetLike(b): return make_Uninhabited() if is_SetLike(a) and is_SetLike(b): a = cast(Type[Set], a) b = cast(Type[Set], b) A = get_SetLike_arg(a) B = get_SetLike_arg(b) u = type_inf(A, B) return make_set(u) if is_DictLike(a) ^ is_DictLike(b): return make_Uninhabited() if is_DictLike(a) and is_DictLike(b): a = cast(Type[Dict], a) b = cast(Type[Dict], b) KA, VA = get_DictLike_args(a) KB, VB = get_DictLike_args(b) K = type_inf(KA, KB) V = type_inf(VA, VB) return make_dict(K, V) if is_dataclass(a) ^ is_dataclass(b): return make_Uninhabited() if is_dataclass(a) and is_dataclass(b): return type_inf_dataclass(a, b) if is_VarTuple(a) and is_VarTuple(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) VA = get_VarTuple_arg(a) VB = get_VarTuple_arg(b) V = type_inf(VA, VB) return make_VarTuple(V) if is_FixedTupleLike(a) and is_FixedTupleLike(b): a = cast(Type[Tuple], a) b = cast(Type[Tuple], b) tas = get_FixedTupleLike_args(a) tbs = get_FixedTupleLike_args(b) ts = tuple(type_inf(ta, tb) for ta, tb in zip(tas, tbs)) return make_Tuple(*ts) if is_TypeVar(a) and is_TypeVar(b): if get_TypeVar_name(a) == get_TypeVar_name(b): return a return make_Intersection((a, b)) @dataclass class MatchConstraint: ub: type = None lb: type = None def impose_subtype(self, ub) -> "MatchConstraint": ub = type_sup(self.ub, ub) if self.ub is not None else ub return MatchConstraint(ub=ub, lb=self.lb) def impose_supertype(self, lb) -> "MatchConstraint": lb = type_inf(self.lb, lb) if self.lb is not None else lb return MatchConstraint(lb=lb, ub=self.ub) @dataclass class Matches: m: Dict[str, MatchConstraint] = field(default_factory=dict) def get_matches(self): res = {} for k, v in self.m.items(): if v.ub is not None: res[k] = v.ub return res def get_ub(self, k: str): if k not in self.m: return None return self.m[k].ub def get_lb(self, k: str): if k not in self.m: return None return self.m[k].lb def must_be_subtype_of(self, k: str, ub) -> "Matches": m2 = dict(self.m) if k not in m2: m2[k] = MatchConstraint() m2[k] = m2[k].impose_subtype(ub=ub) return Matches(m2) def must_be_supertype_of(self, k: str, lb) -> "Matches": m2 = dict(self.m) if k not in m2: m2[k] = MatchConstraint() m2[k] = m2[k].impose_supertype(lb=lb) return Matches(m2)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/type_algebra.py
type_algebra.py
import sys import typing from abc import ABCMeta, abstractmethod from dataclasses import dataclass, fields, is_dataclass from datetime import datetime from decimal import Decimal from typing import Any, ClassVar, Dict, Tuple, cast from zuper_typing.exceptions import ZTypeError, ZValueError from .annotations_tricks import ( get_ClassVar_arg, get_Type_arg, is_ClassVar, is_NewType, is_Type, is_TypeLike, name_for_type_like, ) from .constants import ( BINDINGS_ATT, cache_enabled, DEPENDS_ATT, enable_type_checking, GENERIC_ATT2, MakeTypeCache, PYTHON_36, ZuperTypingGlobals, ) from .logging import logger from .recursive_tricks import ( get_name_without_brackets, NoConstructorImplemented, replace_typevars, TypeLike, ) from .subcheck import can_be_used_as2 def as_tuple(x) -> Tuple: return x if isinstance(x, tuple) else (x,) if PYTHON_36: # pragma: no cover from typing import GenericMeta # noinspection PyUnresolvedReferences old_one = GenericMeta.__getitem__ else: old_one = None if PYTHON_36: # pragma: no cover # logger.info('In Python 3.6') class ZMeta(type): def __getitem__(self, *params): # logger.info(f'ZMeta.__getitem__ {params} {self}') # pprint('P36', params=params, self=self) # if self is typing.Generic: return ZenericFix.__class_getitem__(*params) # # if self is typing.Dict: # K, V = params # if K is not str: # from zuper_typing.my_dict import make_dict # # return make_dict(K, V) # # # noinspection PyArgumentList # return old_one(self, *params) else: ZMeta = type class ZenericFix(metaclass=ZMeta): if PYTHON_36: # pragma: no cover def __getitem__(self, *params): # logger.info(f'P36 {params} {self}') if self is typing.Generic: return ZenericFix.__class_getitem__(*params) if self is Dict: K, V = params if K is not str: from .my_dict import make_dict return make_dict(K, V) # noinspection PyArgumentList return old_one(self, params) # noinspection PyMethodParameters @classmethod def __class_getitem__(cls0, params): # logger.info(f'ZenericFix.__class_getitem__ params = {params}') types = as_tuple(params) assert isinstance(types, tuple) for t in types: assert is_TypeLike(t), (t, types) # types = tuple(map(map_none_to_nonetype, types)) # logger.info(f'types {types}') if PYTHON_36: # pragma: no cover class FakeGenericMeta(MyABC): def __getitem__(self, params2): # logger.info(f'FakeGenericMeta {params2!r} {self}') # pprint('FakeGenericMeta.__getitem__', cls=cls, self=self, # params2=params2) types2 = as_tuple(params2) assert isinstance(types2, tuple), types2 for t in types2: assert is_TypeLike(t), (t, types2) if types == types2: return self bindings = {} for T, U in zip(types, types2): bindings[T] = U if T.__bound__ is not None and isinstance(T.__bound__, type): if not issubclass(U, T.__bound__): msg = ( f'For type parameter "{T.__name__}", expected a' f'subclass of "{T.__bound__.__name__}", found {U}.' ) raise ZTypeError(msg) return make_type(self, bindings) else: FakeGenericMeta = MyABC class GenericProxy(metaclass=FakeGenericMeta): @abstractmethod def need(self) -> None: """""" @classmethod def __class_getitem__(cls, params2) -> type: # logger.info(f'GenericProxy.__class_getitem__ params = {params2}') types2 = as_tuple(params2) bindings = {} for T, U in zip(types, types2): bindings[T] = U if T.__bound__ is not None and isinstance(T.__bound__, type): # logger.info(f"{U} should be usable as {T.__bound__}") # logger.info( # f" issubclass({U}, {T.__bound__}) =" # f" {issubclass(U, T.__bound__)}" # ) if not issubclass(U, T.__bound__): msg = ( f'For type parameter "{T.__name__}", expected a' f'subclass of "{T.__bound__.__name__}", found @U.' ) raise TypeError(msg) # , U=U) res = make_type(cls, bindings) from zuper_typing.monkey_patching_typing import remember_created_class remember_created_class(res, "__class_getitem__") return res name = "Generic[%s]" % ",".join(name_for_type_like(_) for _ in types) gp = type(name, (GenericProxy,), {GENERIC_ATT2: types}) setattr(gp, GENERIC_ATT2, types) return gp class StructuralTyping(type): def __subclasscheck__(self, subclass) -> bool: can = can_be_used_as2(subclass, self) return can.result def __instancecheck__(self, instance) -> bool: T = type(instance) if T is self: return True if not is_dataclass(T): return False i = super().__instancecheck__(instance) if i: return True # # loadable - To remove # if "Loadable" in T.__name__ and hasattr(instance, "T"): # pragma: no cover # if hasattr(instance, "T"): # T = getattr(instance, "T") # can = can_be_used_as2(T, self) # if can.result: # return True res = can_be_used_as2(T, self) return res.result class MyABC(StructuralTyping, ABCMeta): def __new__(mcs, name_orig, bases, namespace, **kwargs): # logger.info(f'----\nCreating name: {name}') # logger.info('namespace: %s' % namespace) # logger.info('bases: %s' % str(bases)) # if bases: # logger.info('bases[0]: %s' % str(bases[0].__dict__)) if GENERIC_ATT2 in namespace: spec = namespace[GENERIC_ATT2] elif bases and GENERIC_ATT2 in bases[0].__dict__: spec = bases[0].__dict__[GENERIC_ATT2] else: spec = {} if spec: name0 = get_name_without_brackets(name_orig) name = f"{name0}[%s]" % (",".join(name_for_type_like(_) for _ in spec)) else: name = name_orig # noinspection PyArgumentList cls = super().__new__(mcs, name, bases, namespace, **kwargs) qn = cls.__qualname__.replace(name_orig, name) setattr(cls, "__qualname__", qn) setattr(cls, "__module__", mcs.__module__) setattr(cls, GENERIC_ATT2, spec) return cls from typing import Optional class Fake: symbols: dict myt: type def __init__(self, myt, symbols: dict): self.myt = myt n = name_for_type_like(myt) self.name_without = get_name_without_brackets(n) self.symbols = symbols def __getitem__(self, item: type) -> type: n = name_for_type_like(item) complete = f"{self.name_without}[{n}]" if complete in self.symbols: return self.symbols[complete] # noinspection PyUnresolvedReferences return self.myt[item] def resolve_types( T, locals_=None, refs: Tuple = (), nrefs: Optional[Dict[str, Any]] = None ): if nrefs is None: nrefs = {} assert is_dataclass(T) # rl = RecLogger() if locals_ is None: locals_ = {} symbols = dict(locals_) for k, v in nrefs.items(): symbols[k] = v others = getattr(T, DEPENDS_ATT, ()) for t in (T,) + refs + others: n = name_for_type_like(t) symbols[n] = t # logger.info(f't = {t} n {n}') name_without = get_name_without_brackets(n) # if name_without in ['Union', 'Dict', ]: # # FIXME please add more here # continue if name_without not in symbols: symbols[name_without] = Fake(t, symbols) # else: # pass for x in getattr(T, GENERIC_ATT2, ()): if hasattr(x, "__name__"): symbols[x.__name__] = x # logger.debug(f'symbols: {symbols}') annotations: Dict[str, TypeLike] = getattr(T, "__annotations__", {}) for k, v in annotations.items(): if not isinstance(v, str) and is_ClassVar(v): continue # XXX v = cast(TypeLike, v) try: r = replace_typevars(v, bindings={}, symbols=symbols) # rl.p(f'{k!r} -> {v!r} -> {r!r}') annotations[k] = r except NameError: msg = ( f"resolve_type({T.__name__}):" f' Cannot resolve names for attribute "{k}" = {v!r}.' ) # msg += f'\n symbols: {symbols}' # msg += '\n\n' + indent(traceback.format_exc(), '', '> ') # raise NameError(msg) from e logger.warning(msg) continue except TypeError as e: # pragma: no cover msg = f'Cannot resolve type for attribute "{k}".' raise ZTypeError(msg) from e for f in fields(T): assert f.name in annotations # msg = f'Cannot get annotation for field {f.name!r}' # logger.warning(msg) # continue f.type = annotations[f.name] def type_check(type_self: type, k: str, T_expected: type, value_found: object): try: T_found = type(value_found) simple = T_found in [int, float, bool, str, bytes, Decimal, datetime] definitely_exclude = T_found in [dict, list, tuple] do_it = (not definitely_exclude) and ( ZuperTypingGlobals.enable_type_checking_difficult or simple ) if do_it: # fail = T_found.__name__ != T_expected.__name__ and not isinstance(value_found, T_expected) ok = can_be_used_as2(T_found, T_expected) if not ok: # pragma: no cover msg = f"The field is not of the expected value" # warnings.warn(msg, stacklevel=3) raise ZValueError( msg, type_self=type_self, field=k, expected_type=T_expected, found_type=T_found, found_value=value_found, why=ok, ) except TypeError as e: # pragma: no cover msg = f"Cannot judge annotation of {k} (supposedly {value_found}." if sys.version_info[:2] == (3, 6): # FIXME: warn return logger.error(msg) raise TypeError(msg) from e def make_type(cls: type, bindings, symbols=None) -> type: if symbols is None: symbols = {} symbols = dict(symbols) assert not is_NewType(cls) if not bindings: return cls cache_key = (str(cls), str(bindings)) if cache_enabled: if cache_key in MakeTypeCache.cache: # print(f'using cached value for {cache_key}') return MakeTypeCache.cache[cache_key] generic_att2 = getattr(cls, GENERIC_ATT2, ()) assert isinstance(generic_att2, tuple) recur = lambda _: replace_typevars(_, bindings=bindings, symbols=symbols) annotations = getattr(cls, "__annotations__", {}) name_without = get_name_without_brackets(cls.__name__) def param_name(x: type) -> str: x2 = recur(x) return name_for_type_like(x2) if generic_att2: name2 = "%s[%s]" % (name_without, ",".join(param_name(_) for _ in generic_att2)) else: name2 = name_without try: cls2 = type(name2, (cls,), {"need": lambda: None}) # logger.info(f'Created class {cls2} ({name2}) and set qualname {cls2.__qualname__}') except TypeError as e: # pragma: no cover msg = f'Cannot create derived class "{name2}" from {cls!r}' raise TypeError(msg) from e symbols[name2] = cls2 symbols[cls.__name__] = cls2 # also MyClass[X] should resolve to the same MakeTypeCache.cache[cache_key] = cls2 class Fake2: def __getitem__(self, item): n = name_for_type_like(item) complete = f"{name_without}[{n}]" if complete in symbols: return symbols[complete] # noinspection PyUnresolvedReferences return cls[item] if name_without not in symbols: symbols[name_without] = Fake2() for T, U in bindings.items(): symbols[T.__name__] = U if hasattr(U, "__name__"): # dict does not have name symbols[U.__name__] = U # first of all, replace the bindings in the generic_att generic_att2_new = tuple(recur(_) for _ in generic_att2) # logger.debug( # f"creating derived class {name2} with abstract method need() because # generic_att2_new = {generic_att2_new}") # rl.p(f' generic_att2_new: {generic_att2_new}') # pprint(f'\n\n{cls.__name__}') # pprint(f'binding', bindings=str(bindings)) # pprint(f'symbols', **symbols) new_annotations = {} # logger.info(f'annotations ({annotations}) ') for k, v0 in annotations.items(): v = recur(v0) # print(f'{v0!r} -> {v!r}') if is_ClassVar(v): s = get_ClassVar_arg(v) if is_Type(s): st = get_Type_arg(s) concrete = recur(st) # logger.info(f'is_Type ({s}) -> {concrete}') # concrete = st new_annotations[k] = ClassVar[type] setattr(cls2, k, concrete) else: s2 = recur(s) new_annotations[k] = ClassVar[s2] else: new_annotations[k] = v # logger.info(f'new_annotations {new_annotations}') # pprint(' new annotations', **new_annotations) original__post_init__ = getattr(cls, "__post_init__", None) if enable_type_checking: def __post_init__(self): # do it first (because they might change things around) if original__post_init__ is not None: original__post_init__(self) for k, T_expected in new_annotations.items(): if is_ClassVar(T_expected): continue if isinstance(T_expected, type): val = getattr(self, k) type_check(type(self), k=k, value_found=val, T_expected=T_expected) # important: do it before dataclass setattr(cls2, "__post_init__", __post_init__) cls2.__annotations__ = new_annotations # logger.info('new annotations: %s' % new_annotations) if is_dataclass(cls): # note: need to have set new annotations # pprint('creating dataclass from %s' % cls2) doc = getattr(cls2, "__doc__", None) cls2 = dataclass(cls2, unsafe_hash=True) setattr(cls2, "__doc__", doc) else: # noinspection PyUnusedLocal def init_placeholder(self, *args, **kwargs): if args or kwargs: msg = ( f"Default constructor of {cls2.__name__} does not know what to do with " f"" f"" f"arguments." ) msg += f"\nargs: {args!r}\nkwargs: {kwargs!r}" msg += f"\nself: {self}" msg += f"\nself: {dir(type(self))}" msg += f"\nself: {type(self)}" raise NoConstructorImplemented(msg) if cls.__init__ == object.__init__: setattr(cls2, "__init__", init_placeholder) cls2.__module__ = cls.__module__ setattr(cls2, "__name__", name2) qn = cls.__qualname__ qn0, sep, _ = qn.rpartition(".") if not sep: sep = "" setattr(cls2, "__qualname__", qn0 + sep + name2) setattr(cls2, BINDINGS_ATT, bindings) setattr(cls2, GENERIC_ATT2, generic_att2_new) MakeTypeCache.cache[cache_key] = cls2 # logger.info(f'started {cls}; hash is {cls.__hash__}') # logger.info(f'specialized {cls2}; hash is {cls2.__hash__}') # ztinfo("make_type", cls=cls, bindings=bindings, cls2=cls2) return cls2
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/zeneric2.py
zeneric2.py
import typing from dataclasses import dataclass as dataclass_orig, Field, is_dataclass from typing import ( Any, cast, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Tuple, Type, TYPE_CHECKING, TypeVar, Union, ) from .aliases import TypeLike from .constants import NAME_ARG, PYTHON_36 paranoid = False def is_TypeLike(x: object) -> bool: if isinstance(x, type): return True else: # noinspection PyTypeChecker return ( is_SpecialForm(x) or is_ClassVar(x) or is_MyNamedArg(x) or is_Type(x) or is_TypeVar(x) ) def is_SpecialForm(x: TypeLike) -> bool: """ Does not include: ClassVar, NamedArg, Type, TypeVar Does include: ForwardRef, NewType, """ if ( is_Any(x) or is_Callable(x) or is_Dict(x) or is_Tuple(x) or is_ForwardRef(x) or is_Iterable(x) or is_Iterator(x) or is_List(x) or is_NewType(x) or is_Optional(x) or is_Sequence(x) or is_Set(x) or is_Tuple(x) or is_Union(x) ): return True return False # noinspection PyProtectedMember def is_Optional(x: TypeLike) -> bool: if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( isinstance(x, typing._Union) and len(x.__args__) >= 2 and x.__args__[-1] is type(None) ) else: # noinspection PyUnresolvedReferences return ( isinstance(x, typing._GenericAlias) and (getattr(x, "__origin__") is Union) and len(x.__args__) >= 2 and x.__args__[-1] is type(None) ) X = TypeVar("X") def get_Optional_arg(x: Type[Optional[X]]) -> Type[X]: assert is_Optional(x) args = x.__args__ if len(args) == 2: return args[0] else: return make_Union(*args[:-1]) # return x.__args__[0] def is_Union(x: TypeLike) -> bool: """ Union[X, None] is not considered a Union""" if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return not is_Optional(x) and isinstance(x, typing._Union) else: # noinspection PyUnresolvedReferences return ( not is_Optional(x) and isinstance(x, typing._GenericAlias) and (x.__origin__ is Union) ) def get_Union_args(x: TypeLike) -> Tuple[TypeLike, ...]: assert is_Union(x), x # noinspection PyUnresolvedReferences return tuple(x.__args__) def key_for_sorting_types(y: TypeLike) -> tuple: if is_TypeVar(y): return (1, get_TypeVar_name(y)) elif is_dataclass(y): return (2, name_for_type_like(y)) elif y is type(None): return (3, "") else: return (0, name_for_type_like(y)) def remove_duplicates(a: Tuple[TypeLike]) -> Tuple[TypeLike]: done = [] for _ in a: assert is_TypeLike(_), a if _ not in done: done.append(_) return tuple(done) def make_Union(*a: TypeLike) -> TypeLike: from zuper_typing.type_algebra import unroll_union r = () for _ in a: assert is_TypeLike(_), a r = r + unroll_union(_) a = r if len(a) == 0: raise ValueError("empty") a = remove_duplicates(a) if len(a) == 1: return a[0] # print(list(map(key_for_sorting_types, a))) if type(None) in a: others = tuple(_ for _ in a if _ is not type(None)) return Optional[make_Union(*others)] a = tuple(sorted(a, key=key_for_sorting_types)) if len(a) == 2: x = Union[a[0], a[1]] elif len(a) == 3: x = Union[a[0], a[1], a[2]] elif len(a) == 4: x = Union[a[0], a[1], a[2], a[3]] elif len(a) == 5: x = Union[a[0], a[1], a[2], a[3], a[4]] else: x = Union.__getitem__(tuple(a)) return x TUPLE_EMPTY_ATTR = "__empty__" class Caches: tuple_caches = {} def make_VarTuple(a: Type[X]) -> Type[Tuple[X, ...]]: args = (a, ...) res = make_Tuple(*args) return res class DummyForEmpty: pass def make_Tuple(*a: TypeLike) -> Type[Tuple]: for _ in a: if isinstance(_, tuple): raise ValueError(a) if a in Caches.tuple_caches: return Caches.tuple_caches[a] if len(a) == 0: x = Tuple[DummyForEmpty] setattr(x, TUPLE_EMPTY_ATTR, True) elif len(a) == 1: x = Tuple[a[0]] elif len(a) == 2: x = Tuple[a[0], a[1]] elif len(a) == 3: x = Tuple[a[0], a[1], a[2]] elif len(a) == 4: x = Tuple[a[0], a[1], a[2], a[3]] elif len(a) == 5: x = Tuple[a[0], a[1], a[2], a[3], a[4]] else: if PYTHON_36: # pragma: no cover x = Tuple[a] else: # NOTE: actually correct # noinspection PyArgumentList x = Tuple.__getitem__(tuple(a)) Caches.tuple_caches[a] = x return x def _check_valid_arg(x: Any) -> None: if not paranoid: return if isinstance(x, str): # pragma: no cover msg = f"The annotations must be resolved: {x!r}" raise ValueError(msg) def is_ForwardRef(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ForwardRef) else: # noinspection PyUnresolvedReferences return isinstance(x, typing.ForwardRef) class CacheFor: cache = {} def make_ForwardRef(n: str) -> TypeLike: if n in CacheFor.cache: return CacheFor.cache[n] if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences res = typing._ForwardRef(n) else: # noinspection PyUnresolvedReferences res = typing.ForwardRef(n) CacheFor.cache[n] = res return res def get_ForwardRef_arg(x: TypeLike) -> str: assert is_ForwardRef(x) # noinspection PyUnresolvedReferences return x.__forward_arg__ def is_Any(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover return x is Any else: # noinspection PyUnresolvedReferences return isinstance(x, typing._SpecialForm) and x._name == "Any" class CacheTypeVar: cache = {} if TYPE_CHECKING: make_TypeVar = TypeVar else: def make_TypeVar( name: str, *, bound: Optional[type] = None, contravariant: bool = False, covariant: bool = False, ) -> TypeVar: key = (name, bound, contravariant, covariant) if key in CacheTypeVar.cache: return CacheTypeVar.cache[key] # noinspection PyTypeHints res = TypeVar( name, bound=bound, contravariant=contravariant, covariant=covariant ) CacheTypeVar.cache[key] = res return res def is_TypeVar(x: TypeLike) -> bool: return isinstance(x, typing.TypeVar) def get_TypeVar_bound(x: TypeVar) -> TypeLike: assert is_TypeVar(x), x bound = x.__bound__ if bound is None: return object else: return bound def get_TypeVar_name(x: TypeVar) -> str: assert is_TypeVar(x), x return x.__name__ def is_ClassVar(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing._ClassVar) else: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x.__origin__ is typing.ClassVar) def get_ClassVar_arg(x: TypeLike) -> TypeLike: # cannot put ClassVar assert is_ClassVar(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return x.__type__ else: # noinspection PyUnresolvedReferences return x.__args__[0] def get_ClassVar_name(x: TypeLike) -> str: # cannot put ClassVar assert is_ClassVar(x), x s = name_for_type_like(get_ClassVar_arg(x)) return f"ClassVar[{s}]" def is_Type(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return (x is typing.Type) or ( isinstance(x, typing.GenericMeta) and (x.__origin__ is typing.Type) ) else: # noinspection PyUnresolvedReferences return (x is typing.Type) or ( isinstance(x, typing._GenericAlias) and (x.__origin__ is type) ) def is_NewType(x: TypeLike) -> bool: _check_valid_arg(x) # if PYTHON_36: # pragma: no cover # # noinspection PyUnresolvedReferences # return (x is typing.Type) or (isinstance(x, typing.GenericMeta) and (x.__origin__ # is typing.Type)) # else: # return (x is typing.Type) or (isinstance(x, typing._GenericAlias) and (x.__origin__ is # type)) return hasattr(x, "__supertype__") def get_NewType_arg(x: TypeLike) -> TypeLike: assert is_NewType(x), x # noinspection PyUnresolvedReferences return x.__supertype__ def get_NewType_name(x: TypeLike) -> str: return x.__name__ def get_NewType_repr(x: TypeLike) -> str: n = get_NewType_name(x) p = get_NewType_arg(x) if is_Any(p) or p is object: return f"NewType({n!r})" else: sp = name_for_type_like(p) return f"NewType({n!r}, {sp})" def is_TupleLike(x: TypeLike) -> bool: from .my_dict import is_CustomTuple return is_Tuple(x) or x is tuple or is_CustomTuple(x) def is_FixedTupleLike(x: TypeLike) -> bool: from .my_dict import is_CustomTuple return is_FixedTuple(x) or is_CustomTuple(x) def is_Tuple(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.TupleMeta) else: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x._name == "Tuple") def is_FixedTuple(x: TypeLike) -> bool: if not is_Tuple(x): return False x = cast(Type[Tuple], x) ts = get_tuple_types(x) # if len(ts) == 0: # return False if len(ts) == 2 and ts[-1] is ...: return False else: return True def is_VarTuple(x: TypeLike) -> bool: if x is tuple: return True if not is_Tuple(x): return False x = cast(Type[Tuple], x) ts = get_tuple_types(x) if len(ts) == 2 and ts[-1] is ...: return True else: return False def get_FixedTuple_args(x: Type[Tuple]) -> Tuple[TypeLike, ...]: assert is_FixedTuple(x), x return get_tuple_types(x) def get_FixedTupleLike_args(x: TypeLike) -> Tuple[TypeLike, ...]: assert is_FixedTupleLike(x), x if is_FixedTuple(x): x = cast(Type[Tuple], x) return get_tuple_types(x) from .my_dict import is_CustomTuple, get_CustomTuple_args, CustomTuple if is_CustomTuple(x): x = cast(Type[CustomTuple], x) return get_CustomTuple_args(x) assert False, x def is_VarTuple_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def is_FixedTuple_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def is_FixedTupleLike_canonical(x: Type[Tuple]) -> bool: return (x is not tuple) and (x is not Tuple) def get_VarTuple_arg(x: Type[Tuple[X, ...]]) -> Type[X]: if x is tuple: return Any assert is_VarTuple(x), x ts = get_tuple_types(x) # if len(ts) == 0: # pragma: no cover # return Any return ts[0] def is_generic_alias(x: TypeLike, name: str) -> bool: # noinspection PyUnresolvedReferences return isinstance(x, typing._GenericAlias) and (x._name == name) def is_List(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.List or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.List ) else: return is_generic_alias(x, "List") def is_Iterator(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.Iterator or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Iterator ) else: return is_generic_alias(x, "Iterator") def is_Iterable(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.Iterable or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Iterable ) else: return is_generic_alias(x, "Iterable") def is_Sequence(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is typing.Sequence or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Sequence ) else: return is_generic_alias(x, "Sequence") def is_placeholder_typevar(x: TypeLike) -> bool: return is_TypeVar(x) and get_TypeVar_name(x) in ["T", "T_co"] def get_Set_arg(x: Type[Set]) -> TypeLike: assert is_Set(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_List_arg(x: Type[List[X]]) -> Type[X]: assert is_List(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def is_List_canonical(x: Type[List]) -> bool: assert is_List(x), x if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return False # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return False return True _K = TypeVar("_K") _V = TypeVar("_V") def get_Dict_args(T: Type[Dict[_K, _V]]) -> Tuple[Type[_K], Type[_V]]: assert is_Dict(T), T if T is Dict: return Any, Any # noinspection PyUnresolvedReferences K, V = T.__args__ if PYTHON_36: # pragma: no cover if is_placeholder_typevar(K): K = Any if is_placeholder_typevar(V): V = Any return K, V _X = TypeVar("_X") def get_Iterator_arg(x: TypeLike) -> TypeLike: # PyCharm has problems assert is_Iterator(x), x # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Iterable_arg(x: TypeLike) -> TypeLike: # PyCharm has problems assert is_Iterable(x), x # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Sequence_arg(x: Type[Sequence[_X]]) -> Type[_X]: assert is_Sequence(x), x # noinspection PyUnresolvedReferences if x.__args__ is None: return Any # noinspection PyUnresolvedReferences t = x.__args__[0] if is_placeholder_typevar(t): return Any return t def get_Type_arg(x: TypeLike) -> TypeLike: assert is_Type(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x.__args__ is None: return type # noinspection PyUnresolvedReferences return x.__args__[0] def is_Callable(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return isinstance(x, typing.CallableMeta) else: return getattr(x, "_name", None) == "Callable" # return hasattr(x, '__origin__') and x.__origin__ is typing.Callable # return isinstance(x, typing._GenericAlias) and x.__origin__.__name__ == "Callable" def is_MyNamedArg(x: object) -> bool: return hasattr(x, NAME_ARG) def get_MyNamedArg_name(x: TypeLike) -> str: assert is_MyNamedArg(x), x return getattr(x, NAME_ARG) def is_Dict(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences return ( x is Dict or isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Dict ) else: return is_generic_alias(x, "Dict") def is_Set(x: TypeLike) -> bool: _check_valid_arg(x) if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if x is typing.Set: return True # noinspection PyUnresolvedReferences return isinstance(x, typing.GenericMeta) and x.__origin__ is typing.Set else: return is_generic_alias(x, "Set") def get_Dict_name(T: Type[Dict]) -> str: assert is_Dict(T), T K, V = get_Dict_args(T) return get_Dict_name_K_V(K, V) def get_Dict_name_K_V(K: TypeLike, V: TypeLike) -> str: return "Dict[%s,%s]" % (name_for_type_like(K), name_for_type_like(V)) def get_Set_name_V(V: TypeLike) -> str: return "Set[%s]" % (name_for_type_like(V)) def get_Union_name(V: TypeLike) -> str: return "Union[%s]" % ",".join(name_for_type_like(_) for _ in get_Union_args(V)) def get_List_name(V: Type[List]) -> str: v = get_List_arg(V) return "List[%s]" % name_for_type_like(v) def get_Type_name(V: TypeLike) -> str: v = get_Type_arg(V) return "Type[%s]" % name_for_type_like(v) def get_Iterator_name(V: Type[Iterator]) -> str: # noinspection PyTypeChecker v = get_Iterator_arg(V) return "Iterator[%s]" % name_for_type_like(v) def get_Iterable_name(V: Type[Iterable[X]]) -> str: # noinspection PyTypeChecker v = get_Iterable_arg(V) return "Iterable[%s]" % name_for_type_like(v) def get_Sequence_name(V: Type[Sequence]) -> str: v = get_Sequence_arg(V) return "Sequence[%s]" % name_for_type_like(v) def get_Optional_name(V: TypeLike) -> str: # cannot use Optional as type arg v = get_Optional_arg(V) return "Optional[%s]" % name_for_type_like(v) def get_Set_name(V: Type[Set]) -> str: v = get_Set_arg(V) return "Set[%s]" % name_for_type_like(v) def get_Tuple_name(V: Type[Tuple]) -> str: return "Tuple[%s]" % ",".join(name_for_type_like(_) for _ in get_tuple_types(V)) def get_FixedTupleLike_name(V: Type[Tuple]) -> str: return "Tuple[%s]" % ",".join( name_for_type_like(_) for _ in get_FixedTupleLike_args(V) ) def get_tuple_types(V: Type[Tuple]) -> Tuple[TypeLike, ...]: if V is tuple: return Any, ... if PYTHON_36: # pragma: no cover # noinspection PyUnresolvedReferences if V.__args__ is None: return Any, ... # noinspection PyUnresolvedReferences args = V.__args__ # XXX if args == (DummyForEmpty,): return () if args == (): if hasattr(V, TUPLE_EMPTY_ATTR): return () else: return Any, ... else: return args def name_for_type_like(x: TypeLike) -> str: from .my_dict import is_DictLike, get_SetLike_name from .my_dict import is_SetLike from .my_dict import get_DictLike_name from .uninhabited import is_Uninhabited if is_Any(x): return "Any" elif isinstance(x, typing.TypeVar): return x.__name__ elif x is type(None): return "NoneType" elif is_Union(x): return get_Union_name(x) elif is_List(x): x = cast(Type[List], x) return get_List_name(x) elif is_Iterator(x): x = cast(Type[Iterator], x) # noinspection PyTypeChecker return get_Iterator_name(x) elif is_Iterable(x): x = cast(Type[Iterable], x) # noinspection PyTypeChecker return get_Iterable_name(x) elif is_Tuple(x): x = cast(Type[Tuple], x) return get_Tuple_name(x) elif is_Set(x): x = cast(Type[Set], x) return get_Set_name(x) elif is_SetLike(x): x = cast(Type[Set], x) return get_SetLike_name(x) elif is_Dict(x): x = cast(Type[Dict], x) return get_Dict_name(x) elif is_DictLike(x): x = cast(Type[Dict], x) return get_DictLike_name(x) elif is_Type(x): return get_Type_name(x) elif is_ClassVar(x): return get_ClassVar_name(x) elif is_Sequence(x): x = cast(Type[Sequence], x) return get_Sequence_name(x) elif is_Optional(x): return get_Optional_name(x) elif is_NewType(x): return get_NewType_repr(x) elif is_ForwardRef(x): a = get_ForwardRef_arg(x) return f"ForwardRef({a!r})" elif is_Uninhabited(x): return "!" elif is_Callable(x): info = get_Callable_info(x) # params = ','.join(name_for_type_like(p) for p in info.parameters_by_position) def ps(k, v): if k.startswith("__"): return name_for_type_like(v) else: return f"NamedArg({name_for_type_like(v)},{k!r})" params = ",".join(ps(k, v) for k, v in info.parameters_by_name.items()) ret = name_for_type_like(info.returns) return f"Callable[[{params}],{ret}]" elif x is typing.IO: return str(x) # TODO: should get the attribute elif hasattr(x, "__name__"): # logger.info(f'not matching __name__ {type(x)} {x!r}') return x.__name__ else: # logger.info(f'not matching {type(x)} {x!r}') return str(x) # do not make a dataclass class CallableInfo: parameters_by_name: Dict[str, TypeLike] parameters_by_position: Tuple[TypeLike, ...] ordering: Tuple[str, ...] returns: TypeLike def __init__(self, parameters_by_name, parameters_by_position, ordering, returns): for k, v in parameters_by_name.items(): assert not is_MyNamedArg(v), v for v in parameters_by_position: assert not is_MyNamedArg(v), v self.parameters_by_name = parameters_by_name self.parameters_by_position = parameters_by_position self.ordering = ordering self.returns = returns def __repr__(self) -> str: return ( f"CallableInfo({self.parameters_by_name!r}, {self.parameters_by_position!r}, " f"{self.ordering}, {self.returns})" ) def replace(self, f: typing.Callable[[Any], Any]) -> "CallableInfo": parameters_by_name = {k: f(v) for k, v in self.parameters_by_name.items()} parameters_by_position = tuple(f(v) for v in self.parameters_by_position) ordering = self.ordering returns = f(self.returns) return CallableInfo( parameters_by_name, parameters_by_position, ordering, returns ) def as_callable(self) -> typing.Callable: args = [] for k, v in self.parameters_by_name.items(): # if is_MyNamedArg(v): # # try: # v = v.original # TODO: add MyNamedArg args.append(v) # noinspection PyTypeHints return typing.Callable[args, self.returns] def get_Callable_info(x: Type[typing.Callable]) -> CallableInfo: assert is_Callable(x), x parameters_by_name = {} parameters_by_position = [] ordering = [] args = x.__args__ if args: returns = args[-1] rest = args[:-1] else: returns = Any rest = () for i, a in enumerate(rest): if is_MyNamedArg(a): name = get_MyNamedArg_name(a) t = a.original # t = a else: name = f"{i}" t = a parameters_by_name[name] = t ordering.append(name) parameters_by_position.append(t) return CallableInfo( parameters_by_name=parameters_by_name, parameters_by_position=tuple(parameters_by_position), ordering=tuple(ordering), returns=returns, ) def get_fields_including_static(x: Type[dataclass_orig]) -> Dict[str, Field]: """ returns the fields including classvars """ from dataclasses import _FIELDS fields = getattr(x, _FIELDS) return fields
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/annotations_tricks.py
annotations_tricks.py
from typing import Tuple from zuper_typing.aliases import TypeLike from zuper_typing.annotations_tricks import ( name_for_type_like, key_for_sorting_types, is_TypeLike, ) from .constants import INTERSECTION_ATT, PYTHON_36 if PYTHON_36: # pragma: no cover class IntersectionMeta(type): def __getitem__(self, params): return make_Intersection(params) class Intersection(metaclass=IntersectionMeta): pass else: class Intersection: @classmethod def __class_getitem__(cls, params): # return Intersection_item(cls, params) return make_Intersection(params) class IntersectionCache: use_cache = True make_intersection_cache = {} def make_Intersection(ts: Tuple[TypeLike, ...]) -> TypeLike: if len(ts) == 0: return object done = [] for t in ts: assert is_TypeLike(t), ts if t not in done: done.append(t) done = sorted(done, key=key_for_sorting_types) ts = tuple(done) if len(ts) == 1: return ts[0] if IntersectionCache.use_cache: if ts in IntersectionCache.make_intersection_cache: return IntersectionCache.make_intersection_cache[ts] class IntersectionBase(type): def __eq__(self, other): if is_Intersection(other): t1 = get_Intersection_args(self) t2 = get_Intersection_args(other) return set(t1) == set(t2) return False def __hash__(cls): # pragma: no cover return 1 # XXX # logger.debug(f'here ___eq__ {self} {other} {issubclass(other, CustomList)} = {res}') attrs = {INTERSECTION_ATT: ts} name = "Intersection[%s]" % ",".join(name_for_type_like(_) for _ in ts) res = IntersectionBase(name, (), attrs) IntersectionCache.make_intersection_cache[ts] = res return res def is_Intersection(T: TypeLike) -> bool: return hasattr(T, INTERSECTION_ATT) def get_Intersection_args(T: TypeLike) -> Tuple[TypeLike, ...]: assert is_Intersection(T) return getattr(T, INTERSECTION_ATT)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/my_intersection.py
my_intersection.py
from datetime import datetime from decimal import Decimal from numbers import Number from typing import ( Any, cast, ClassVar, Dict, Iterator, List, Optional, Sequence, Set, Tuple, Type, Union, ) from zuper_typing.literal import is_Literal from .aliases import TypeLike from .annotations_tricks import ( get_Callable_info, get_ClassVar_arg, get_FixedTupleLike_args, get_ForwardRef_arg, get_Iterator_arg, get_List_arg, get_Optional_arg, get_Sequence_arg, get_Type_arg, get_TypeVar_name, get_Union_args, get_VarTuple_arg, is_Any, is_Callable, is_ClassVar, is_FixedTupleLike, is_FixedTupleLike_canonical, is_ForwardRef, is_Iterator, is_List, is_List_canonical, is_NewType, is_Optional, is_Sequence, is_Type, is_TypeVar, is_Union, is_VarTuple, is_VarTuple_canonical, make_Tuple, make_Union, make_VarTuple, ) from .my_dict import ( CustomList, get_CustomList_arg, get_DictLike_args, get_ListLike_arg, get_SetLike_arg, is_CustomList, is_DictLike, is_DictLike_canonical, is_ListLike, is_ListLike_canonical, is_SetLike, is_SetLike_canonical, make_dict, make_list, make_set, ) from .my_intersection import get_Intersection_args, is_Intersection, make_Intersection from .uninhabited import is_Uninhabited def get_name_without_brackets(name: str) -> str: if "[" in name: return name[: name.index("[")] else: return name class NoConstructorImplemented(TypeError): pass def get_default_attrs(): return dict( Any=Any, Optional=Optional, Union=Union, Tuple=Tuple, List=List, Set=Set, Dict=Dict, ) def canonical(typelike: TypeLike) -> TypeLike: return replace_typevars(typelike, bindings={}, symbols={}, make_canonical=True) def replace_typevars( cls: TypeLike, *, bindings: Dict[Any, TypeLike], symbols: Dict[str, TypeLike], make_canonical: bool = False, ) -> TypeLike: from .logging import logger r = lambda _: replace_typevars(_, bindings=bindings, symbols=symbols) if cls is type: return type if hasattr(cls, "__name__") and cls.__name__ in symbols: return symbols[cls.__name__] elif (isinstance(cls, str) or is_TypeVar(cls)) and cls in bindings: return bindings[cls] elif hasattr(cls, "__name__") and cls.__name__.startswith("Placeholder"): return cls elif is_TypeVar(cls): name = get_TypeVar_name(cls) for k, v in bindings.items(): if is_TypeVar(k) and get_TypeVar_name(k) == name: return v return cls # return bindings[cls] elif isinstance(cls, str): if cls in symbols: return symbols[cls] g = dict(get_default_attrs()) g.update(symbols) g0 = dict(g) try: return eval(cls, g) except NameError as e: msg = f"Cannot resolve {cls!r}\ng: {list(g0)}" # msg += 'symbols: {list(g0)' raise NameError(msg) from e elif is_NewType(cls): return cls elif is_Type(cls): x = get_Type_arg(cls) r = r(x) if x == r: return cls return Type[r] # return type elif is_DictLike(cls): cls = cast(Type[Dict], cls) is_canonical = is_DictLike_canonical(cls) K0, V0 = get_DictLike_args(cls) K = r(K0) V = r(V0) # logger.debug(f'{K0} -> {K}; {V0} -> {V}') if (K0, V0) == (K, V) and (is_canonical or not make_canonical): return cls res = make_dict(K, V) return res elif is_SetLike(cls): cls = cast(Type[Set], cls) is_canonical = is_SetLike_canonical(cls) V0 = get_SetLike_arg(cls) V = r(V0) if V0 == V and (is_canonical or not make_canonical): return cls return make_set(V) elif is_CustomList(cls): cls = cast(Type[CustomList], cls) V0 = get_CustomList_arg(cls) V = r(V0) if V0 == V: return cls return make_list(V) elif is_List(cls): cls = cast(Type[List], cls) arg = get_List_arg(cls) is_canonical = is_List_canonical(cls) arg2 = r(arg) if arg == arg2 and (is_canonical or not make_canonical): return cls return List[arg2] elif is_ListLike(cls): cls = cast(Type[List], cls) arg = get_ListLike_arg(cls) is_canonical = is_ListLike_canonical(cls) arg2 = r(arg) if arg == arg2 and (is_canonical or not make_canonical): return cls return make_list(arg2) # XXX NOTE: must go after CustomDict elif hasattr(cls, "__annotations__"): from zuper_typing.zeneric2 import make_type cls2 = make_type(cls, bindings=bindings, symbols=symbols) # ztinfo("replace_typevars", bindings=bindings, cls=cls, cls2=cls2) # logger.info(f'old cls: {cls.__annotations__}') # logger.info(f'new cls2: {cls2.__annotations__}') return cls2 elif is_ClassVar(cls): is_canonical = True # XXXis_ClassVar_canonical(cls) x = get_ClassVar_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return ClassVar[r] elif is_Iterator(cls): is_canonical = True # is_Iterator_canonical(cls) # noinspection PyTypeChecker x = get_Iterator_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return Iterator[r] elif is_Sequence(cls): is_canonical = True # is_Sequence_canonical(cls) cls = cast(Type[Sequence], cls) x = get_Sequence_arg(cls) r = r(x) if x == r and (is_canonical or not make_canonical): return cls return Sequence[r] elif is_Optional(cls): is_canonical = True # is_Optional_canonical(cls) x = get_Optional_arg(cls) x2 = r(x) if x == x2 and (is_canonical or not make_canonical): return cls return Optional[x2] elif is_Union(cls): # cls = cast(Type[Union], cls) cannot cast xs = get_Union_args(cls) is_canonical = True # is_Union_canonical(cls) ys = tuple(r(_) for _ in xs) if ys == xs and (is_canonical or not make_canonical): return cls return make_Union(*ys) elif is_Intersection(cls): xs = get_Intersection_args(cls) ys = tuple(r(_) for _ in xs) if ys == xs: return cls return make_Intersection(ys) elif is_VarTuple(cls): cls = cast(Type[Tuple], cls) is_canonical = is_VarTuple_canonical(cls) X = get_VarTuple_arg(cls) Y = r(X) if X == Y and (is_canonical or not make_canonical): return cls return make_VarTuple(Y) elif is_FixedTupleLike(cls): cls = cast(Type[Tuple], cls) is_canonical = is_FixedTupleLike_canonical(cls) xs = get_FixedTupleLike_args(cls) ys = tuple(r(_) for _ in xs) if ys == xs and (is_canonical or not make_canonical): return cls return make_Tuple(*ys) elif is_Callable(cls): cinfo = get_Callable_info(cls) cinfo2 = cinfo.replace(r) return cinfo2.as_callable() elif is_ForwardRef(cls): T = get_ForwardRef_arg(cls) if T in symbols: return r(symbols[T]) else: logger.warning(f"could not resolve {cls}") return cls elif cls in ( int, bool, float, Decimal, datetime, str, bytes, Number, type(None), object, ): return cls elif is_Any(cls): return cls elif is_Uninhabited(cls): return cls elif is_Literal(cls): return cls elif isinstance(cls, type): # logger.warning(f"extraneous class {cls}") return cls # elif is_Literal(cls): # return cls else: raise NotImplementedError(cls) # logger.debug(f'Nothing to do with {cls!r} {cls}') # return cls B = Dict[Any, Any] # bug in Python 3.6
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing/recursive_tricks.py
recursive_tricks.py
from typing import TypeVar from zuper_typing.annotations_tricks import ( get_TypeVar_bound, get_TypeVar_name, is_TypeVar, ) def test_typevars1(): X = TypeVar("X") assert is_TypeVar(X) assert get_TypeVar_name(X) == "X" assert get_TypeVar_bound(X) is object def test_typevars2(): Y = TypeVar("Y", bound=int) assert is_TypeVar(Y) assert get_TypeVar_name(Y) == "Y" assert get_TypeVar_bound(Y) is int
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_typevar.py
test_typevar.py
from typing import ClassVar, TYPE_CHECKING, Type, TypeVar from nose.tools import assert_equal, raises from zuper_typing.annotations_tricks import ( get_ClassVar_arg, get_Type_arg, is_ClassVar, is_Type, ) from zuper_typing.constants import enable_type_checking from zuper_typing.subcheck import can_be_used_as2 if TYPE_CHECKING: from dataclasses import dataclass from typing import Generic else: from zuper_typing import dataclass, Generic def test_basic(): U = TypeVar("U") T = Generic[U] # print(T.mro()) assert_equal(T.__name__, "Generic[U]") # print("inheriting C(T)") @dataclass class C(T): ... # print(C.mro()) assert_equal(C.__name__, "C[U]") # print("subscribing C[int]") D = C[int] assert_equal(D.__name__, "C[int]") @raises(TypeError) def test_dataclass_can_preserve_init(): X = TypeVar("X") @dataclass class M(Generic[X]): x: int M(x=2) def test_isClassVar(): X = TypeVar("X") A = ClassVar[Type[X]] assert is_ClassVar(A) assert get_ClassVar_arg(A) == Type[X] def test_isType(): X = TypeVar("X") A = Type[X] # print(type(A)) # print(A.__dict__) assert is_Type(A) assert get_Type_arg(A) == X # assert_object_roundtrip(x, {}) @raises(TypeError) def test_check_bound1(): @dataclass class Animal: a: int assert not can_be_used_as2(int, Animal).result assert not issubclass(int, Animal) X = TypeVar("X", bound=Animal) @dataclass class CG(Generic[X]): a: X _ = CG[int] # boom, int !< Animal @raises(TypeError) def test_check_bound2(): @dataclass class Animal: a: int class Not: b: int assert not can_be_used_as2(Not, Animal).result X = TypeVar("X", bound=Animal) @dataclass class CG(Generic[X]): a: X _ = CG[Not] # boom, Not !< Animal # assert_type_roundtrip(CG, {}) # assert_type_roundtrip(CG[int], {}) # if enable_type_checking: @raises(ValueError, TypeError) # typerror in 3.6 def test_check_value(): @dataclass class CG(Generic[()]): a: int CG[int](a="a") if __name__ == "__main__": test_check_bound1()
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_zeneric.py
test_zeneric.py
from typing import Set from nose.tools import assert_equal from zuper_typing.my_dict import get_SetLike_name, make_set def test_set_1(): X = Set[int] n = get_SetLike_name(X) assert_equal(n, "Set[int]") def test_set_2(): X = make_set(int) n = get_SetLike_name(X) assert_equal(n, "Set[int]")
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_set.py
test_set.py
from dataclasses import dataclass from typing import List, Set from zuper_typing import debug_print from zuper_typing.annotations_tricks import get_Set_arg, is_Any, is_List, is_Set from zuper_typing.my_dict import ( get_ListLike_arg, get_SetLike_arg, is_ListLike, is_SetLike, make_dict, make_set, assert_good_typelike, ) def test_dict_hash(): s = set() s2 = set() D = make_dict(str, str) d = D() s.add(d) s2.add(d) def test_set_hash(): s = set() s2 = set() D = make_set(str) d = D() s.add(d) s2.add(d) def test_set_misc01(): assert is_SetLike(Set) def test_set_misc02(): assert is_SetLike(Set[int]) def test_set_misc03(): assert is_SetLike(set) def test_set_misc04(): assert is_SetLike(make_set(int)) def test_set_getvalue01(): assert is_Set(Set[int]) assert get_SetLike_arg(Set[int]) is int def test_set_getvalue02(): assert is_Set(Set) x = get_Set_arg(Set) assert is_Any(x), x x = get_SetLike_arg(Set) assert is_Any(x), x def test_set_getvalue03(): assert get_SetLike_arg(make_set(int)) is int def test_set_getvalue04(): assert is_Any(get_SetLike_arg(set)) def test_list_is01(): assert is_List(List) def test_list_is02(): assert is_List(List[int]) def test_list_is03(): assert not is_List(list) def test_list_arg01(): x = get_ListLike_arg(List) assert is_Any(x), x def test_list_arg02(): x = get_ListLike_arg(list) assert is_Any(x), x def test_list_arg03(): assert get_ListLike_arg(List[int]) is int def test_islist_01(): assert is_ListLike(list) def test_islist_02(): assert is_ListLike(List) def test_islist_03(): assert is_ListLike(List[int]) def test_name(): @dataclass class A: pass # a = A() # assert_good_typelike(A()) debug_print(A) debug_print(A())
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_others.py
test_others.py
from abc import ABCMeta, abstractmethod from typing import ClassVar, TYPE_CHECKING, Type, TypeVar if TYPE_CHECKING: from dataclasses import dataclass from typing import Generic else: from zuper_typing import dataclass from zuper_typing import Generic from dataclasses import is_dataclass from nose.tools import raises, assert_equal from zuper_typing.constants import BINDINGS_ATT # from zuper_ipce_tests.test_utils import assert_object_roundtrip from zuper_typing.recursive_tricks import NoConstructorImplemented X = TypeVar("X") @raises(TypeError) def test_boxed1(): @dataclass class Boxed(Generic[X]): inside: X # cannot instance yet Boxed(inside=13) # assert_object_roundtrip(n1, {'Boxed': Boxed}) def test_boxed2(): @dataclass class BoxedZ(Generic[X]): inside: X # print(BoxedZ.__eq__) C = BoxedZ[int] # print(pretty_dict('BoxedZ[int]', C.__dict__)) assert_equal(C.__annotations__, {"inside": int}) n1 = C(inside=13) # assert_object_roundtrip(n1, use_globals={"BoxedZ": BoxedZ}) @raises(TypeError) def test_boxed_cannot(): # without @dataclass class CannotInstantiateYet(Generic[X]): inside: X # print(CannotInstantiateYet.__init__) # noinspection PyArgumentList CannotInstantiateYet(inside=13) @raises(TypeError) def test_boxed_cannot2(): class CannotInstantiateYet(Generic[X]): inside: X # print(CannotInstantiateYet.__init__) # assert_equal(CannotInstantiateYet.__init__.__name__, 'cannot_instantiate') CI = dataclass(CannotInstantiateYet) # print(CannotInstantiateYet.__init__) # assert_equal(CannotInstantiateYet.__init__.__name__, 'new_init') # print(CI.__init__) CI(inside=13) def test_boxed_can_dataclass(): @dataclass class CannotInstantiateYet(Generic[X]): inside: X # print("name: %s %s" % (CannotInstantiateYet.__name__, CannotInstantiateYet)) assert ( "CannotInstantiateYet" in CannotInstantiateYet.__name__ ), CannotInstantiateYet.__name__ assert is_dataclass(CannotInstantiateYet) # print("calling") CanBeInstantiated = CannotInstantiateYet[str] assert ( "CannotInstantiateYet[str]" in CanBeInstantiated.__name__ ), CanBeInstantiated.__name__ # print("CanBeInstantiated: %s %s" % (CanBeInstantiated.__name__, CanBeInstantiated)) # print(CanBeInstantiated.__init__) CanBeInstantiated(inside="13") def test_boxed_can_with_dataclass(): @dataclass class CannotInstantiateYet(Generic[X]): inside: X CanBeInstantiated = CannotInstantiateYet[str] CanBeInstantiated(inside="12") class Animal(metaclass=ABCMeta): @abstractmethod def verse(self): """verse""" class Dog(Animal): def verse(self): return "wof" @raises(NoConstructorImplemented) def test_parametric_zeneric(): A = TypeVar("A", bound=Animal) class Parametric(Generic[A]): inside: A AT: ClassVar[Type[A]] # def check_knows_type(self, Specific): # T = type(self) # a: A = type(self).AT() # a.verse() # # assert (self.AT is getattr(T, BINDINGS_ATT)[A]) # assert (self.AT is Specific), (self.AT, id(self.AT), Specific, id(Specific)) fido = Dog() PDog = Parametric[Dog] assert "inside" not in PDog.__dict__, PDog.__dict__ assert "AT" in PDog.__dict__, PDog.__dict__ PDog(inside=fido) # p.check_knows_type(Dog) def test_parametric_zeneric_dataclass(): A = TypeVar("A", bound=Animal) @dataclass class Parametric(Generic[A]): inside: A AT: ClassVar[Type[A]] def check_knows_type(self, Specific): T = type(self) a: A = type(self).AT() a.verse() assert self.AT is getattr(T, BINDINGS_ATT)[A] assert self.AT is Specific, (self.AT, id(self.AT), Specific, id(Specific)) fido = Dog() PDog = Parametric[Dog] assert "inside" not in PDog.__dict__, PDog.__dict__ assert "AT" in PDog.__dict__, PDog.__dict__ p = PDog(inside=fido) p.check_knows_type(Dog) # # # @raises(NoConstructorImplemented) # def test_parametric_zeneric(): # try: # _do_parametric(lambda _: _) # except NoConstructorImplemented: # print('ok test_parametric_zeneric') # else: # pass # # raise AssertionError # # # def test_parametric_zeneric_dataclass(): # _do_parametric(dataclass) # print('ok test_parametric_zeneric_dataclass') if __name__ == "__main__": test_parametric_zeneric_dataclass() test_parametric_zeneric()
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_boxed.py
test_boxed.py
from nose.tools import raises from zuper_typing import dataclass from zuper_typing.subcheck import can_be_used_as2 def test_nominal_no_nominal(): @dataclass class A: a: int @dataclass class C: nominal = True @dataclass class D: pass assert not can_be_used_as2(A, C) assert can_be_used_as2(A, D) @raises(TypeError) def test_nominal_inherit(): """ this is a limitation of the spec """ @dataclass class A: a: int nominal = True @dataclass class B(A): b: int
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_nominal.py
test_nominal.py
from typing import Iterable, List from zuper_typing.annotations_tricks import get_Iterable_arg, get_List_arg, is_Any from zuper_typing.my_dict import make_list, get_ListLike_arg, get_ListLike_name def test_list_1(): X = get_List_arg(List) assert is_Any(X), X def test_iterable1(): # noinspection PyTypeChecker X = get_Iterable_arg(Iterable) assert is_Any(X), X def test_iterable2(): X = get_Iterable_arg(Iterable[int]) assert X is int, X def test_list_2(): X = int a = make_list(X) X2 = get_ListLike_arg(a) assert X == X2 def test_list_name_2(): X = int a = make_list(X) n = get_ListLike_name(a) assert n == "List[int]"
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_list.py
test_list.py
from dataclasses import dataclass from typing import Optional, Union from zuper_typing.subcheck import can_be_used_as2 from zuper_typing.zeneric2 import resolve_types def test_recursive1(): @dataclass class T1: data: int branch: "Optional[T1]" resolve_types(T1) @dataclass class T2: data: int branch: "Optional[T2]" resolve_types(T2) # print(T1.__annotations__) # print(T2.__annotations__) # # print(T1) # print(T2) c = can_be_used_as2(T1, T2) # print(c) assert c.result, c.why def test_recursive2(): @dataclass class T1: data: int branch: "Union[T1, int]" resolve_types(T1) @dataclass class T2: data: int branch: "T2" resolve_types(T2) # print(T1) # print(T2) c = can_be_used_as2(T2, T1) # print(c) assert c.result, c.why
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_recursive.py
test_recursive.py
from dataclasses import dataclass from typing import ( Any, ClassVar, Dict, List, NewType, Optional, Set, Tuple, Type, TypeVar, Union, ) from nose.tools import assert_equal, raises from zuper_typing.annotations_tricks import is_Dict, is_List, is_Set from zuper_typing.get_patches_ import assert_equivalent_types, NotEquivalentException from zuper_typing.monkey_patching_typing import original_dict_getitem from zuper_typing.my_dict import make_CustomTuple, make_dict, make_list, make_set from zuper_typing.my_intersection import make_Intersection def test_eq_list1(): a = make_list(int) b = make_list(int) assert a == b assert_equal(a, b) def test_eq_set(): a = make_set(int) b = make_set(int) assert a == b assert_equal(a, b) def test_eq_dict(): a = make_dict(int, str) b = make_dict(int, str) assert a == b assert_equal(a, b) def test_eq_list2(): a = make_list(int) b = List[int] # print(type(a), type(b)) assert is_List(b), type(b) assert not is_List(a), a assert a == b def test_eq_dict2(): a = make_dict(int, str) # print(original_dict_getitem) b = original_dict_getitem((int, str)) # print(type(a), type(b)) assert is_Dict(b), type(b) assert not is_Dict(a), a assert a == b def test_eq_set2(): a = make_set(int) b = Set[int] # print(type(a), type(b)) assert is_Set(b), type(b) assert not is_Set(a), a assert a == b @raises(NotEquivalentException) def test_cover_equiv0(): @dataclass class Eq1: pass assert_equivalent_types(Eq1, bool) @raises(NotEquivalentException) def test_cover_equiv1(): @dataclass class Eq2: pass assert_equivalent_types(bool, Eq2) @raises(NotEquivalentException) def test_cover_equiv2(): @dataclass class Eq3: pass @dataclass class Eq4: a: int assert_equivalent_types(Eq4, Eq3) @raises(NotEquivalentException) def test_cover_equiv03(): assert_equivalent_types(ClassVar[int], bool) @raises(NotEquivalentException) def test_cover_equiv04(): assert_equivalent_types(Dict[int, bool], bool) @raises(NotEquivalentException) def test_cover_equiv05(): assert_equivalent_types(List[int], bool) @raises(NotEquivalentException) def test_cover_equiv06(): assert_equivalent_types(Any, bool) @raises(NotEquivalentException) def test_cover_equiv07(): assert_equivalent_types(Set[int], bool) @raises(NotEquivalentException) def test_cover_equiv08(): X = TypeVar("X") assert_equivalent_types(X, bool) @raises(NotEquivalentException) def test_cover_equiv09(): X = TypeVar("X") Y = TypeVar("Y") assert_equivalent_types(X, Y) def test_cover_equiv09b(): X = TypeVar("X") Y = TypeVar("X") assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv10(): X = Tuple[int, bool] assert_equivalent_types(X, bool) @raises(NotEquivalentException) def test_cover_equiv11(): X = Tuple[int, ...] assert_equivalent_types(X, bool) @raises(NotEquivalentException) def test_cover_equiv12(): X = Tuple[int, bool] Y = Tuple[int, str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv13(): X = Tuple[int, ...] Y = Tuple[bool, ...] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv14(): X = Optional[int] Y = Optional[bool] assert_equivalent_types(X, Y) # @raises(NotEquivalentException) def test_cover_equiv15(): X = make_CustomTuple((int, str)) Y = Tuple[int, str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv16_set(): X = Set[int] Y = Set[bool] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv17(): X = Union[int, str] Y = Union[bool, str] assert_equivalent_types(X, Y) def test_cover_equiv17b(): X = Union[bool, str] Y = Union[bool, str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv17c(): X = Union[bool, str, float] Y = Union[bool, str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv17c(): X = Union[bool, str] Y = int assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv18_set(): X = List[int] Y = List[bool] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv19(): X = Dict[int, int] Y = Dict[bool, int] assert_equivalent_types(X, Y) def test_cover_equiv20(): X = make_dict(int, int) Y = Dict[int, int] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv21(): X = Any Y = int assert_equivalent_types(X, Y) def test_cover_equiv22(): X = Any Y = Any assert_equivalent_types(X, Y) def test_cover_equiv23(): X = NewType("a", int) Y = NewType("a", int) assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv24(): X = NewType("a", int) Y = NewType("b", int) assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv25(): X = NewType("a", bool) Y = NewType("a", int) assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv26(): X = NewType("a", bool) Y = int assert_equivalent_types(X, Y) def test_cover_equiv27(): X = Type Y = Type assert_equivalent_types(X, Y) def test_cover_equiv28(): X = Type[int] Y = Type[int] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv29(): X = Type[int] Y = Type[str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv30(): X = Type[int] Y = str assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv31(): X = Optional[int] Y = str assert_equivalent_types(X, Y) def test_cover_equiv32(): X = Optional[str] Y = Optional[str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv33(): X = Optional[int] Y = Optional[str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv34(): X = int Y = str assert_equivalent_types(X, Y) def test_cover_equiv35(): X = ClassVar[int] Y = ClassVar[int] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv36(): X = ClassVar[int] Y = ClassVar[str] assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv37(): X = ClassVar[int] Y = int assert_equivalent_types(X, Y) def test_cover_equiv38(): X = make_Intersection((int, bool)) Y = make_Intersection((int, bool)) assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv39(): X = make_Intersection((int, bool)) Y = make_Intersection((int, str)) assert_equivalent_types(X, Y) @raises(NotEquivalentException) def test_cover_equiv40(): X = make_Intersection((int, bool)) Y = int assert_equivalent_types(X, Y)
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_equalities.py
test_equalities.py
from typing import Any, Dict, List, Set, Tuple from zuper_commons.text import pretty_dict from zuper_typing.annotations_tricks import ( is_VarTuple, is_VarTuple_canonical, make_VarTuple, get_VarTuple_arg, is_Any, is_FixedTuple, ) from zuper_typing.my_dict import make_dict, make_list, make_set from zuper_typing.recursive_tricks import canonical def test_canonical(): cases = [ (dict, make_dict(Any, Any)), (Dict, make_dict(Any, Any)), (list, make_list(Any)), (List, make_list(Any)), (tuple, make_VarTuple(Any)), (Tuple, make_VarTuple(Any)), (set, make_set(Any)), (Set, make_set(Any)), ] for a, b in cases: yield check_canonical, a, b def check_canonical(a, expected): obtained = canonical(a) if obtained != expected: msg = "Failure" raise Exception( pretty_dict(msg, dict(a=a, obtained=obtained, expected=expected)) ) def test_canonical1(): assert is_VarTuple(tuple) assert not is_FixedTuple(tuple) assert is_Any(get_VarTuple_arg(tuple)) assert not is_VarTuple_canonical(tuple) r = canonical(tuple) assert r == Tuple[Any, ...], r
zuper-typing-z5
/zuper-typing-z5-5.3.0.tar.gz/zuper-typing-z5-5.3.0/src/zuper_typing_tests/test_canonical.py
test_canonical.py