repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
wtolson/gnsq
gnsq/nsqd.py
NsqdTCPClient.publish
def publish(self, topic, data, defer=None): """Publish a message to the given topic over tcp. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6) """ ...
python
def publish(self, topic, data, defer=None): """Publish a message to the given topic over tcp. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6) """ ...
Publish a message to the given topic over tcp. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6)
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L418-L431
wtolson/gnsq
gnsq/nsqd.py
NsqdTCPClient.multipublish
def multipublish(self, topic, messages): """Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish """ self.send(nsq.multipublish(topic, messages))
python
def multipublish(self, topic, messages): """Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish """ self.send(nsq.multipublish(topic, messages))
Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L433-L440
wtolson/gnsq
gnsq/nsqd.py
NsqdTCPClient.ready
def ready(self, count): """Indicate you are ready to receive ``count`` messages.""" self.ready_count = count self.send(nsq.ready(count))
python
def ready(self, count): """Indicate you are ready to receive ``count`` messages.""" self.ready_count = count self.send(nsq.ready(count))
Indicate you are ready to receive ``count`` messages.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L442-L445
wtolson/gnsq
gnsq/nsqd.py
NsqdTCPClient.finish
def finish(self, message_id): """Finish a message (indicate successful processing).""" self.send(nsq.finish(message_id)) self.finish_inflight() self.on_finish.send(self, message_id=message_id)
python
def finish(self, message_id): """Finish a message (indicate successful processing).""" self.send(nsq.finish(message_id)) self.finish_inflight() self.on_finish.send(self, message_id=message_id)
Finish a message (indicate successful processing).
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L447-L451
wtolson/gnsq
gnsq/nsqd.py
NsqdTCPClient.requeue
def requeue(self, message_id, timeout=0, backoff=True): """Re-queue a message (indicate failure to process).""" self.send(nsq.requeue(message_id, timeout)) self.finish_inflight() self.on_requeue.send( self, message_id=message_id, timeout=timeout, ...
python
def requeue(self, message_id, timeout=0, backoff=True): """Re-queue a message (indicate failure to process).""" self.send(nsq.requeue(message_id, timeout)) self.finish_inflight() self.on_requeue.send( self, message_id=message_id, timeout=timeout, ...
Re-queue a message (indicate failure to process).
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L453-L462
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.publish
def publish(self, topic, data, defer=None): """Publish a message to the given topic over http. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in millisconds to defer before publishing (requires nsq 0.3.6) """ ...
python
def publish(self, topic, data, defer=None): """Publish a message to the given topic over http. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in millisconds to defer before publishing (requires nsq 0.3.6) """ ...
Publish a message to the given topic over http. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in millisconds to defer before publishing (requires nsq 0.3.6)
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L507-L523
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.multipublish
def multipublish(self, topic, messages, binary=False): """Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param binary: enable binary mode. defaults to False (requires ...
python
def multipublish(self, topic, messages, binary=False): """Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param binary: enable binary mode. defaults to False (requires ...
Publish an iterable of messages to the given topic over http. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param binary: enable binary mode. defaults to False (requires nsq 1.0.0) By default multipublish expects messages to be...
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L531-L554
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.create_topic
def create_topic(self, topic): """Create a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/create', fields={'topic': topic})
python
def create_topic(self, topic): """Create a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/create', fields={'topic': topic})
Create a topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L556-L559
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.delete_topic
def delete_topic(self, topic): """Delete a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/delete', fields={'topic': topic})
python
def delete_topic(self, topic): """Delete a topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/delete', fields={'topic': topic})
Delete a topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L561-L564
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.empty_topic
def empty_topic(self, topic): """Empty all the queued messages for an existing topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/empty', fields={'topic': topic})
python
def empty_topic(self, topic): """Empty all the queued messages for an existing topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/empty', fields={'topic': topic})
Empty all the queued messages for an existing topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L580-L583
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.empty_channel
def empty_channel(self, topic, channel): """Empty all the queued messages for an existing channel.""" nsq.assert_valid_topic_name(topic) nsq.assert_valid_channel_name(channel) return self._request('POST', '/channel/empty', fields={'topic': topic, 'channel': c...
python
def empty_channel(self, topic, channel): """Empty all the queued messages for an existing channel.""" nsq.assert_valid_topic_name(topic) nsq.assert_valid_channel_name(channel) return self._request('POST', '/channel/empty', fields={'topic': topic, 'channel': c...
Empty all the queued messages for an existing channel.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L585-L590
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.pause_topic
def pause_topic(self, topic): """Pause message flow to all channels on an existing topic. Messages will queue at topic. """ nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/pause', fields={'topic': topic})
python
def pause_topic(self, topic): """Pause message flow to all channels on an existing topic. Messages will queue at topic. """ nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/pause', fields={'topic': topic})
Pause message flow to all channels on an existing topic. Messages will queue at topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L592-L598
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.unpause_topic
def unpause_topic(self, topic): """Resume message flow to channels of an existing, paused, topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/unpause', fields={'topic': topic})
python
def unpause_topic(self, topic): """Resume message flow to channels of an existing, paused, topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/unpause', fields={'topic': topic})
Resume message flow to channels of an existing, paused, topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L600-L603
wtolson/gnsq
gnsq/nsqd.py
NsqdHTTPClient.stats
def stats(self, topic=None, channel=None, text=False): """Return internal instrumented statistics. :param topic: (optional) filter to topic :param channel: (optional) filter to channel :param text: return the stats as a string (default: ``False``) """ if text: ...
python
def stats(self, topic=None, channel=None, text=False): """Return internal instrumented statistics. :param topic: (optional) filter to topic :param channel: (optional) filter to channel :param text: return the stats as a string (default: ``False``) """ if text: ...
Return internal instrumented statistics. :param topic: (optional) filter to topic :param channel: (optional) filter to channel :param text: return the stats as a string (default: ``False``)
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L622-L644
wtolson/gnsq
gnsq/nsqd.py
Nsqd.publish_tcp
def publish_tcp(self, topic, data, **kwargs): """Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0 """ return self.__tcp_client.publish(topic, data, **kwargs)
python
def publish_tcp(self, topic, data, **kwargs): """Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0 """ return self.__tcp_client.publish(topic, data, **kwargs)
Use :meth:`NsqdTCPClient.publish` instead. .. deprecated:: 1.0.0
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L682-L687
wtolson/gnsq
gnsq/nsqd.py
Nsqd.publish_http
def publish_http(self, topic, data, **kwargs): """Use :meth:`NsqdHTTPClient.publish` instead. .. deprecated:: 1.0.0 """ self.__http_client.publish(topic, data, **kwargs)
python
def publish_http(self, topic, data, **kwargs): """Use :meth:`NsqdHTTPClient.publish` instead. .. deprecated:: 1.0.0 """ self.__http_client.publish(topic, data, **kwargs)
Use :meth:`NsqdHTTPClient.publish` instead. .. deprecated:: 1.0.0
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L690-L695
wtolson/gnsq
gnsq/nsqd.py
Nsqd.multipublish_tcp
def multipublish_tcp(self, topic, messages, **kwargs): """Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0 """ return self.__tcp_client.multipublish(topic, messages, **kwargs)
python
def multipublish_tcp(self, topic, messages, **kwargs): """Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0 """ return self.__tcp_client.multipublish(topic, messages, **kwargs)
Use :meth:`NsqdTCPClient.multipublish` instead. .. deprecated:: 1.0.0
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L704-L709
wtolson/gnsq
gnsq/nsqd.py
Nsqd.multipublish_http
def multipublish_http(self, topic, messages, **kwargs): """Use :meth:`NsqdHTTPClient.multipublish` instead. .. deprecated:: 1.0.0 """ return self.__http_client.multipublish(topic, messages, **kwargs)
python
def multipublish_http(self, topic, messages, **kwargs): """Use :meth:`NsqdHTTPClient.multipublish` instead. .. deprecated:: 1.0.0 """ return self.__http_client.multipublish(topic, messages, **kwargs)
Use :meth:`NsqdHTTPClient.multipublish` instead. .. deprecated:: 1.0.0
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/nsqd.py#L712-L717
wtolson/gnsq
gnsq/producer.py
Producer.start
def start(self): """Start discovering and listing to connections.""" if self._state == CLOSED: raise NSQException('producer already closed') if self.is_running: self.logger.warn('producer already started') return self.logger.debug('starting producer....
python
def start(self): """Start discovering and listing to connections.""" if self._state == CLOSED: raise NSQException('producer already closed') if self.is_running: self.logger.warn('producer already started') return self.logger.debug('starting producer....
Start discovering and listing to connections.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L98-L112
wtolson/gnsq
gnsq/producer.py
Producer.close
def close(self): """Immediately close all connections and stop workers.""" if not self.is_running: return self._state = CLOSED self.logger.debug('closing connection(s)') while True: try: conn = self._connections.get(block=False) ...
python
def close(self): """Immediately close all connections and stop workers.""" if not self.is_running: return self._state = CLOSED self.logger.debug('closing connection(s)') while True: try: conn = self._connections.get(block=False) ...
Immediately close all connections and stop workers.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L114-L130
wtolson/gnsq
gnsq/producer.py
Producer.join
def join(self, timeout=None, raise_error=False): """Block until all connections have closed and workers stopped.""" self._workers.join(timeout, raise_error)
python
def join(self, timeout=None, raise_error=False): """Block until all connections have closed and workers stopped.""" self._workers.join(timeout, raise_error)
Block until all connections have closed and workers stopped.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L132-L134
wtolson/gnsq
gnsq/producer.py
Producer.publish
def publish(self, topic, data, defer=None, block=True, timeout=None, raise_error=True): """Publish a message to the given topic. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publish...
python
def publish(self, topic, data, defer=None, block=True, timeout=None, raise_error=True): """Publish a message to the given topic. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publish...
Publish a message to the given topic. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6) :param block: wait for a connection to become available before ...
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L252-L287
wtolson/gnsq
gnsq/producer.py
Producer.multipublish
def multipublish(self, topic, messages, block=True, timeout=None, raise_error=True): """Publish an iterable of messages to the given topic. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param block: wait for a connectio...
python
def multipublish(self, topic, messages, block=True, timeout=None, raise_error=True): """Publish an iterable of messages to the given topic. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param block: wait for a connectio...
Publish an iterable of messages to the given topic. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param block: wait for a connection to become available before publishing the message. If block is `False` and no connections a...
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/producer.py#L289-L321
wtolson/gnsq
gnsq/message.py
Message.finish
def finish(self): """ Respond to nsqd that you’ve processed this message successfully (or would like to silently discard it). """ if self._has_responded: raise NSQException('already responded') self._has_responded = True self.on_finish.send(self)
python
def finish(self): """ Respond to nsqd that you’ve processed this message successfully (or would like to silently discard it). """ if self._has_responded: raise NSQException('already responded') self._has_responded = True self.on_finish.send(self)
Respond to nsqd that you’ve processed this message successfully (or would like to silently discard it).
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/message.py#L59-L67
wtolson/gnsq
gnsq/message.py
Message.requeue
def requeue(self, time_ms=0, backoff=True): """ Respond to nsqd that you’ve failed to process this message successfully (and would like it to be requeued). """ if self._has_responded: raise NSQException('already responded') self._has_responded = True s...
python
def requeue(self, time_ms=0, backoff=True): """ Respond to nsqd that you’ve failed to process this message successfully (and would like it to be requeued). """ if self._has_responded: raise NSQException('already responded') self._has_responded = True s...
Respond to nsqd that you’ve failed to process this message successfully (and would like it to be requeued).
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/message.py#L69-L77
wtolson/gnsq
gnsq/lookupd.py
LookupdClient.lookup
def lookup(self, topic): """Returns producers for a topic.""" nsq.assert_valid_topic_name(topic) return self._request('GET', '/lookup', fields={'topic': topic})
python
def lookup(self, topic): """Returns producers for a topic.""" nsq.assert_valid_topic_name(topic) return self._request('GET', '/lookup', fields={'topic': topic})
Returns producers for a topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/lookupd.py#L26-L29
wtolson/gnsq
gnsq/lookupd.py
LookupdClient.channels
def channels(self, topic): """Returns all known channels of a topic.""" nsq.assert_valid_topic_name(topic) return self._request('GET', '/channels', fields={'topic': topic})
python
def channels(self, topic): """Returns all known channels of a topic.""" nsq.assert_valid_topic_name(topic) return self._request('GET', '/channels', fields={'topic': topic})
Returns all known channels of a topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/lookupd.py#L35-L38
wtolson/gnsq
gnsq/lookupd.py
LookupdClient.tombstone_topic
def tombstone_topic(self, topic, node): """Tombstones a specific producer of an existing topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/tombstone', fields={'topic': topic, 'node': node})
python
def tombstone_topic(self, topic, node): """Tombstones a specific producer of an existing topic.""" nsq.assert_valid_topic_name(topic) return self._request('POST', '/topic/tombstone', fields={'topic': topic, 'node': node})
Tombstones a specific producer of an existing topic.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/lookupd.py#L68-L72
wtolson/gnsq
gnsq/consumer.py
Consumer.start
def start(self, block=True): """Start discovering and listing to connections.""" if self._state == INIT: if not any(self.on_message.receivers_for(blinker.ANY)): raise RuntimeError('no receivers connected to on_message') self.logger.debug('starting %s...', self.na...
python
def start(self, block=True): """Start discovering and listing to connections.""" if self._state == INIT: if not any(self.on_message.receivers_for(blinker.ANY)): raise RuntimeError('no receivers connected to on_message') self.logger.debug('starting %s...', self.na...
Start discovering and listing to connections.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/consumer.py#L229-L249
wtolson/gnsq
gnsq/consumer.py
Consumer.close
def close(self): """Immediately close all connections and stop workers.""" if not self.is_running: return self._state = CLOSED self.logger.debug('killing %d worker(s)', len(self._killables)) self._killables.kill(block=False) self.logger.debug('closing %d co...
python
def close(self): """Immediately close all connections and stop workers.""" if not self.is_running: return self._state = CLOSED self.logger.debug('killing %d worker(s)', len(self._killables)) self._killables.kill(block=False) self.logger.debug('closing %d co...
Immediately close all connections and stop workers.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/consumer.py#L251-L265
wtolson/gnsq
gnsq/reader.py
Reader.publish
def publish(self, topic, message): """Use :class:`~gnsq.Producer` instead. .. deprecated:: 1.0.0 """ if not self.connections: raise NSQNoConnections() conn = random.choice(list(self.connections)) conn.publish(topic, message)
python
def publish(self, topic, message): """Use :class:`~gnsq.Producer` instead. .. deprecated:: 1.0.0 """ if not self.connections: raise NSQNoConnections() conn = random.choice(list(self.connections)) conn.publish(topic, message)
Use :class:`~gnsq.Producer` instead. .. deprecated:: 1.0.0
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/reader.py#L57-L65
wtolson/gnsq
gnsq/decorators.py
deprecated
def deprecated(fn): """Mark a function as deprecated and warn the user on use.""" @functools.wraps(fn) def wrapper(*args, **kwargs): warnings.warn(fn.__doc__.split('\n')[0], category=DeprecationWarning, stacklevel=2) return fn(*args, **kwargs) return wrapper
python
def deprecated(fn): """Mark a function as deprecated and warn the user on use.""" @functools.wraps(fn) def wrapper(*args, **kwargs): warnings.warn(fn.__doc__.split('\n')[0], category=DeprecationWarning, stacklevel=2) return fn(*args, **kwargs) return wrapper
Mark a function as deprecated and warn the user on use.
https://github.com/wtolson/gnsq/blob/0fd02578b2c9c5fa30626d78579db2a46c10edac/gnsq/decorators.py#L26-L33
llllllllll/codetransformer
codetransformer/core.py
_new_lnotab
def _new_lnotab(instrs, lnotab): """The updated lnotab after the instructions have been transformed. Parameters ---------- instrs : iterable[Instruction] The new instructions. lnotab : dict[Instruction -> int] The lnotab for the old code object. Returns ------- new_lnot...
python
def _new_lnotab(instrs, lnotab): """The updated lnotab after the instructions have been transformed. Parameters ---------- instrs : iterable[Instruction] The new instructions. lnotab : dict[Instruction -> int] The lnotab for the old code object. Returns ------- new_lnot...
The updated lnotab after the instructions have been transformed. Parameters ---------- instrs : iterable[Instruction] The new instructions. lnotab : dict[Instruction -> int] The lnotab for the old code object. Returns ------- new_lnotab : dict[Instruction -> int] Th...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/core.py#L32-L50
llllllllll/codetransformer
codetransformer/core.py
CodeTransformer.transform_consts
def transform_consts(self, consts): """transformer for the co_consts field. Override this method to transform the `co_consts` of the code object. Parameters ---------- consts : tuple The co_consts Returns ------- new_consts : tuple ...
python
def transform_consts(self, consts): """transformer for the co_consts field. Override this method to transform the `co_consts` of the code object. Parameters ---------- consts : tuple The co_consts Returns ------- new_consts : tuple ...
transformer for the co_consts field. Override this method to transform the `co_consts` of the code object. Parameters ---------- consts : tuple The co_consts Returns ------- new_consts : tuple The new constants.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/core.py#L104-L124
llllllllll/codetransformer
codetransformer/core.py
CodeTransformer.transform
def transform(self, code, *, name=None, filename=None): """Transform a codetransformer.Code object applying the transforms. Parameters ---------- code : Code The code object to transform. name : str, optional The new name for this code object. fil...
python
def transform(self, code, *, name=None, filename=None): """Transform a codetransformer.Code object applying the transforms. Parameters ---------- code : Code The code object to transform. name : str, optional The new name for this code object. fil...
Transform a codetransformer.Code object applying the transforms. Parameters ---------- code : Code The code object to transform. name : str, optional The new name for this code object. filename : str, optional The new filename for this code ob...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/core.py#L150-L204
llllllllll/codetransformer
codetransformer/utils/pretty.py
pformat_ast
def pformat_ast(node, include_attributes=INCLUDE_ATTRIBUTES_DEFAULT, indent=INDENT_DEFAULT): """ Pretty-format an AST tree element Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whether to include...
python
def pformat_ast(node, include_attributes=INCLUDE_ATTRIBUTES_DEFAULT, indent=INDENT_DEFAULT): """ Pretty-format an AST tree element Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whether to include...
Pretty-format an AST tree element Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whether to include node attributes. Default False. indent : str, optional. Indentation string for nested expressions. Default is two spaces.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L31-L108
llllllllll/codetransformer
codetransformer/utils/pretty.py
pprint_ast
def pprint_ast(node, include_attributes=INCLUDE_ATTRIBUTES_DEFAULT, indent=INDENT_DEFAULT, file=None): """ Pretty-print an AST tree. Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whe...
python
def pprint_ast(node, include_attributes=INCLUDE_ATTRIBUTES_DEFAULT, indent=INDENT_DEFAULT, file=None): """ Pretty-print an AST tree. Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whe...
Pretty-print an AST tree. Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whether to include node attributes. Default False. indent : str, optional. Indentation string for nested expressions. Default is two spaces. file...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L117-L146
llllllllll/codetransformer
codetransformer/utils/pretty.py
walk_code
def walk_code(co, _prefix=''): """ Traverse a code object, finding all consts which are also code objects. Yields pairs of (name, code object). """ name = _prefix + co.co_name yield name, co yield from chain.from_iterable( walk_code(c, _prefix=_extend_name(name, co)) for c i...
python
def walk_code(co, _prefix=''): """ Traverse a code object, finding all consts which are also code objects. Yields pairs of (name, code object). """ name = _prefix + co.co_name yield name, co yield from chain.from_iterable( walk_code(c, _prefix=_extend_name(name, co)) for c i...
Traverse a code object, finding all consts which are also code objects. Yields pairs of (name, code object).
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L149-L161
llllllllll/codetransformer
codetransformer/utils/pretty.py
a
def a(text, mode='exec', indent=' ', file=None): """ Interactive convenience for displaying the AST of a code string. Writes a pretty-formatted AST-tree to `file`. Parameters ---------- text : str Text of Python code to render as AST. mode : {'exec', 'eval'}, optional Mode...
python
def a(text, mode='exec', indent=' ', file=None): """ Interactive convenience for displaying the AST of a code string. Writes a pretty-formatted AST-tree to `file`. Parameters ---------- text : str Text of Python code to render as AST. mode : {'exec', 'eval'}, optional Mode...
Interactive convenience for displaying the AST of a code string. Writes a pretty-formatted AST-tree to `file`. Parameters ---------- text : str Text of Python code to render as AST. mode : {'exec', 'eval'}, optional Mode for `ast.parse`. Default is 'exec'. indent : str, option...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L172-L190
llllllllll/codetransformer
codetransformer/utils/pretty.py
d
def d(obj, mode='exec', file=None): """ Interactive convenience for displaying the disassembly of a function, module, or code string. Compiles `text` and recursively traverses the result looking for `code` objects to render with `dis.dis`. Parameters ---------- obj : str, CodeType, or ...
python
def d(obj, mode='exec', file=None): """ Interactive convenience for displaying the disassembly of a function, module, or code string. Compiles `text` and recursively traverses the result looking for `code` objects to render with `dis.dis`. Parameters ---------- obj : str, CodeType, or ...
Interactive convenience for displaying the disassembly of a function, module, or code string. Compiles `text` and recursively traverses the result looking for `code` objects to render with `dis.dis`. Parameters ---------- obj : str, CodeType, or object with __code__ attribute Object to...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L193-L221
llllllllll/codetransformer
codetransformer/utils/pretty.py
extract_code
def extract_code(obj, compile_mode): """ Generic function for converting objects into instances of `CodeType`. """ try: code = obj.__code__ if isinstance(code, CodeType): return code raise ValueError( "{obj} has a `__code__` attribute, " "but i...
python
def extract_code(obj, compile_mode): """ Generic function for converting objects into instances of `CodeType`. """ try: code = obj.__code__ if isinstance(code, CodeType): return code raise ValueError( "{obj} has a `__code__` attribute, " "but i...
Generic function for converting objects into instances of `CodeType`.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L225-L241
llllllllll/codetransformer
codetransformer/utils/pretty.py
display
def display(text, mode='exec', file=None): """ Show `text`, rendered as AST and as Bytecode. Parameters ---------- text : str Text of Python code to render. mode : {'exec', 'eval'}, optional Mode for `ast.parse` and `compile`. Default is 'exec'. file : None or file-like obj...
python
def display(text, mode='exec', file=None): """ Show `text`, rendered as AST and as Bytecode. Parameters ---------- text : str Text of Python code to render. mode : {'exec', 'eval'}, optional Mode for `ast.parse` and `compile`. Default is 'exec'. file : None or file-like obj...
Show `text`, rendered as AST and as Bytecode. Parameters ---------- text : str Text of Python code to render. mode : {'exec', 'eval'}, optional Mode for `ast.parse` and `compile`. Default is 'exec'. file : None or file-like object, optional File to use to print output. If ...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/pretty.py#L275-L304
llllllllll/codetransformer
codetransformer/transformers/pattern_matched_exceptions.py
match
def match(match_expr, exc_type, exc_value, exc_traceback): """ Called to determine whether or not an except block should be matched. True -> enter except block False -> don't enter except block """ # Emulate standard behavior when match_expr is an exception subclass. if isinstance(match_exp...
python
def match(match_expr, exc_type, exc_value, exc_traceback): """ Called to determine whether or not an except block should be matched. True -> enter except block False -> don't enter except block """ # Emulate standard behavior when match_expr is an exception subclass. if isinstance(match_exp...
Called to determine whether or not an except block should be matched. True -> enter except block False -> don't enter except block
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/pattern_matched_exceptions.py#L15-L31
llllllllll/codetransformer
codetransformer/decompiler/_343.py
decompile
def decompile(f): """ Decompile a function. Parameters ---------- f : function The function to decompile. Returns ------- ast : ast.FunctionDef A FunctionDef node that compiles to f. """ co = f.__code__ args, kwonly, varargs, varkwargs = paramnames(co) a...
python
def decompile(f): """ Decompile a function. Parameters ---------- f : function The function to decompile. Returns ------- ast : ast.FunctionDef A FunctionDef node that compiles to f. """ co = f.__code__ args, kwonly, varargs, varkwargs = paramnames(co) a...
Decompile a function. Parameters ---------- f : function The function to decompile. Returns ------- ast : ast.FunctionDef A FunctionDef node that compiles to f.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L52-L97
llllllllll/codetransformer
codetransformer/decompiler/_343.py
pycode_to_body
def pycode_to_body(co, context): """ Convert a Python code object to a list of AST body elements. """ code = Code.from_pycode(co) # On each instruction, temporarily store all the jumps to the **next** # instruction. This is used in _make_expr to determine when an expression # is part of a ...
python
def pycode_to_body(co, context): """ Convert a Python code object to a list of AST body elements. """ code = Code.from_pycode(co) # On each instruction, temporarily store all the jumps to the **next** # instruction. This is used in _make_expr to determine when an expression # is part of a ...
Convert a Python code object to a list of AST body elements.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L100-L121
llllllllll/codetransformer
codetransformer/decompiler/_343.py
instrs_to_body
def instrs_to_body(instrs, context): """ Convert a list of Instruction objects to a list of AST body nodes. """ stack = [] body = [] process_instrs(instrs, stack, body, context) if stack: raise DecompilationError( "Non-empty stack at the end of instrs_to_body(): %s." % s...
python
def instrs_to_body(instrs, context): """ Convert a list of Instruction objects to a list of AST body nodes. """ stack = [] body = [] process_instrs(instrs, stack, body, context) if stack: raise DecompilationError( "Non-empty stack at the end of instrs_to_body(): %s." % s...
Convert a list of Instruction objects to a list of AST body nodes.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L124-L136
llllllllll/codetransformer
codetransformer/decompiler/_343.py
process_instrs
def process_instrs(queue, stack, body, context): """ Process instructions from the instruction queue. """ next_instr = queue.popleft while queue: newcontext = _process_instr(next_instr(), queue, stack, body, context) if newcontext is not None: context = newcontext
python
def process_instrs(queue, stack, body, context): """ Process instructions from the instruction queue. """ next_instr = queue.popleft while queue: newcontext = _process_instr(next_instr(), queue, stack, body, context) if newcontext is not None: context = newcontext
Process instructions from the instruction queue.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L139-L147
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_if_statement
def make_if_statement(instr, queue, stack, context): """ Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE. """ test_expr = make_expr(stack) if isinstance(instr, instrs.POP_JUMP_IF_TRUE): test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr) first_block = popwhile(op....
python
def make_if_statement(instr, queue, stack, context): """ Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE. """ test_expr = make_expr(stack) if isinstance(instr, instrs.POP_JUMP_IF_TRUE): test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr) first_block = popwhile(op....
Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L182-L211
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_process_instr_import_name
def _process_instr_import_name(instr, queue, stack, body, context): """ Process an IMPORT_NAME instruction. Side Effects ------------ Pops two instuctions from `stack` Consumes instructions from `queue` to the end of the import statement. Appends an ast.Import or ast.ImportFrom node to `bod...
python
def _process_instr_import_name(instr, queue, stack, body, context): """ Process an IMPORT_NAME instruction. Side Effects ------------ Pops two instuctions from `stack` Consumes instructions from `queue` to the end of the import statement. Appends an ast.Import or ast.ImportFrom node to `bod...
Process an IMPORT_NAME instruction. Side Effects ------------ Pops two instuctions from `stack` Consumes instructions from `queue` to the end of the import statement. Appends an ast.Import or ast.ImportFrom node to `body`.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L226-L283
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_pop_import_LOAD_ATTRs
def _pop_import_LOAD_ATTRs(module_name, queue): """ Pop LOAD_ATTR instructions for an import of the form:: import a.b.c as d which should generate bytecode like this:: 1 0 LOAD_CONST 0 (0) 3 LOAD_CONST 1 (None) ...
python
def _pop_import_LOAD_ATTRs(module_name, queue): """ Pop LOAD_ATTR instructions for an import of the form:: import a.b.c as d which should generate bytecode like this:: 1 0 LOAD_CONST 0 (0) 3 LOAD_CONST 1 (None) ...
Pop LOAD_ATTR instructions for an import of the form:: import a.b.c as d which should generate bytecode like this:: 1 0 LOAD_CONST 0 (0) 3 LOAD_CONST 1 (None) 6 IMPORT_NAME 0 (a.b.c.d) 9...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L286-L312
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_importfrom_alias
def make_importfrom_alias(queue, body, context, name): """ Make an ast.alias node for the names list of an ast.ImportFrom. Parameters ---------- queue : deque Instruction Queue body : list Current body. context : DecompilationContext name : str Expected name of t...
python
def make_importfrom_alias(queue, body, context, name): """ Make an ast.alias node for the names list of an ast.ImportFrom. Parameters ---------- queue : deque Instruction Queue body : list Current body. context : DecompilationContext name : str Expected name of t...
Make an ast.alias node for the names list of an ast.ImportFrom. Parameters ---------- queue : deque Instruction Queue body : list Current body. context : DecompilationContext name : str Expected name of the IMPORT_FROM node to be popped. Returns ------- alia...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L316-L350
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_make_function
def _make_function(instr, queue, stack, body, context): """ Set a make_function_context, then push onto the stack. """ assert stack, "Empty stack before MAKE_FUNCTION." prev = stack[-1] expect(prev, instrs.LOAD_CONST, "before MAKE_FUNCTION") stack.append(instr) if is_lambda_name(prev.a...
python
def _make_function(instr, queue, stack, body, context): """ Set a make_function_context, then push onto the stack. """ assert stack, "Empty stack before MAKE_FUNCTION." prev = stack[-1] expect(prev, instrs.LOAD_CONST, "before MAKE_FUNCTION") stack.append(instr) if is_lambda_name(prev.a...
Set a make_function_context, then push onto the stack.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L385-L402
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_assignment
def make_assignment(instr, queue, stack): """ Make an ast.Assign node. """ value = make_expr(stack) # Make assignment targets. # If there are multiple assignments (e.g. 'a = b = c'), # each LHS expression except the last is preceded by a DUP_TOP instruction. # Thus, we make targets unti...
python
def make_assignment(instr, queue, stack): """ Make an ast.Assign node. """ value = make_expr(stack) # Make assignment targets. # If there are multiple assignments (e.g. 'a = b = c'), # each LHS expression except the last is preceded by a DUP_TOP instruction. # Thus, we make targets unti...
Make an ast.Assign node.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L429-L447
llllllllll/codetransformer
codetransformer/decompiler/_343.py
pop_with_body_instrs
def pop_with_body_instrs(setup_with_instr, queue): """ Pop instructions from `queue` that form the body of a with block. """ body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left') # Last two instructions should always be POP_BLOCK, LOAD_CONST(None). # These don't correspond...
python
def pop_with_body_instrs(setup_with_instr, queue): """ Pop instructions from `queue` that form the body of a with block. """ body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left') # Last two instructions should always be POP_BLOCK, LOAD_CONST(None). # These don't correspond...
Pop instructions from `queue` that form the body of a with block.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L574-L599
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_withitem
def make_withitem(queue, stack): """ Make an ast.withitem node. """ context_expr = make_expr(stack) # This is a POP_TOP for just "with <expr>:". # This is a STORE_NAME(name) for "with <expr> as <name>:". as_instr = queue.popleft() if isinstance(as_instr, (instrs.STORE_FAST, ...
python
def make_withitem(queue, stack): """ Make an ast.withitem node. """ context_expr = make_expr(stack) # This is a POP_TOP for just "with <expr>:". # This is a STORE_NAME(name) for "with <expr> as <name>:". as_instr = queue.popleft() if isinstance(as_instr, (instrs.STORE_FAST, ...
Make an ast.withitem node.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L602-L623
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_for_loop
def make_for_loop(loop_body_instrs, else_body_instrs, context): """ Make an ast.For node. """ # Instructions from start until GET_ITER are the builders for the iterator # expression. iterator_expr = make_expr( popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left') ) # N...
python
def make_for_loop(loop_body_instrs, else_body_instrs, context): """ Make an ast.For node. """ # Instructions from start until GET_ITER are the builders for the iterator # expression. iterator_expr = make_expr( popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left') ) # N...
Make an ast.For node.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L636-L669
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_loop_body_and_orelse
def make_loop_body_and_orelse(top_of_loop, body_instrs, else_instrs, context): """ Make body and orelse lists for a for/while loop whose first instruction is `top_of_loop`. Parameters ---------- top_of_loop : Instruction The first body of the loop. For a for-loop, this should always be...
python
def make_loop_body_and_orelse(top_of_loop, body_instrs, else_instrs, context): """ Make body and orelse lists for a for/while loop whose first instruction is `top_of_loop`. Parameters ---------- top_of_loop : Instruction The first body of the loop. For a for-loop, this should always be...
Make body and orelse lists for a for/while loop whose first instruction is `top_of_loop`. Parameters ---------- top_of_loop : Instruction The first body of the loop. For a for-loop, this should always be a FOR_ITER. For a while loop, it's the first instruction of the stack bui...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L672-L710
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_while_loop
def make_while_loop(test_and_body_instrs, else_body_instrs, context): """ Make an ast.While node. Parameters ---------- test_and_body_instrs : deque Queue of instructions forming the loop test expression and body. else_body_instrs : deque Queue of instructions forming the else b...
python
def make_while_loop(test_and_body_instrs, else_body_instrs, context): """ Make an ast.While node. Parameters ---------- test_and_body_instrs : deque Queue of instructions forming the loop test expression and body. else_body_instrs : deque Queue of instructions forming the else b...
Make an ast.While node. Parameters ---------- test_and_body_instrs : deque Queue of instructions forming the loop test expression and body. else_body_instrs : deque Queue of instructions forming the else block of the loop. context : DecompilationContext
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L713-L736
llllllllll/codetransformer
codetransformer/decompiler/_343.py
pop_loop_instrs
def pop_loop_instrs(setup_loop_instr, queue): """ Determine whether setup_loop_instr is setting up a for-loop or a while-loop. Then pop the loop instructions from queue. The easiest way to tell the difference is to look at the target of the JUMP_ABSOLUTE instruction at the end of the loop. If it ...
python
def pop_loop_instrs(setup_loop_instr, queue): """ Determine whether setup_loop_instr is setting up a for-loop or a while-loop. Then pop the loop instructions from queue. The easiest way to tell the difference is to look at the target of the JUMP_ABSOLUTE instruction at the end of the loop. If it ...
Determine whether setup_loop_instr is setting up a for-loop or a while-loop. Then pop the loop instructions from queue. The easiest way to tell the difference is to look at the target of the JUMP_ABSOLUTE instruction at the end of the loop. If it jumps to a FOR_ITER, then this is a for-loop. Otherwi...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L784-L839
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_make_expr
def _make_expr(toplevel, stack_builders): """ Override the single-dispatched make_expr with wrapper logic for handling short-circuiting expressions. """ base_expr = _make_expr_internal(toplevel, stack_builders) if not toplevel._next_target_of: return base_expr subexprs = deque([base...
python
def _make_expr(toplevel, stack_builders): """ Override the single-dispatched make_expr with wrapper logic for handling short-circuiting expressions. """ base_expr = _make_expr_internal(toplevel, stack_builders) if not toplevel._next_target_of: return base_expr subexprs = deque([base...
Override the single-dispatched make_expr with wrapper logic for handling short-circuiting expressions.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L856-L881
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_boolop
def make_boolop(exprs, op_types): """ Parameters ---------- exprs : deque op_types : deque[{ast.And, ast.Or}] """ if len(op_types) > 1: return ast.BoolOp( op=op_types.popleft(), values=[exprs.popleft(), make_boolop(exprs, op_types)], ) assert len(...
python
def make_boolop(exprs, op_types): """ Parameters ---------- exprs : deque op_types : deque[{ast.And, ast.Or}] """ if len(op_types) > 1: return ast.BoolOp( op=op_types.popleft(), values=[exprs.popleft(), make_boolop(exprs, op_types)], ) assert len(...
Parameters ---------- exprs : deque op_types : deque[{ast.And, ast.Or}]
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L884-L898
llllllllll/codetransformer
codetransformer/decompiler/_343.py
normalize_boolop
def normalize_boolop(expr): """ Normalize a boolop by folding together nested And/Or exprs. """ optype = expr.op newvalues = [] for subexpr in expr.values: if not isinstance(subexpr, ast.BoolOp): newvalues.append(subexpr) elif type(subexpr.op) != type(optype): ...
python
def normalize_boolop(expr): """ Normalize a boolop by folding together nested And/Or exprs. """ optype = expr.op newvalues = [] for subexpr in expr.values: if not isinstance(subexpr, ast.BoolOp): newvalues.append(subexpr) elif type(subexpr.op) != type(optype): ...
Normalize a boolop by folding together nested And/Or exprs.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L901-L916
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_call_keywords
def make_call_keywords(stack_builders, count): """ Make the keywords entry for an ast.Call node. """ out = [] for _ in range(count): value = make_expr(stack_builders) load_kwname = stack_builders.pop() if not isinstance(load_kwname, instrs.LOAD_CONST): raise Decom...
python
def make_call_keywords(stack_builders, count): """ Make the keywords entry for an ast.Call node. """ out = [] for _ in range(count): value = make_expr(stack_builders) load_kwname = stack_builders.pop() if not isinstance(load_kwname, instrs.LOAD_CONST): raise Decom...
Make the keywords entry for an ast.Call node.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1040-L1058
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_call_positionals
def make_call_positionals(stack_builders, count): """ Make the args entry for an ast.Call node. """ out = [make_expr(stack_builders) for _ in range(count)] out.reverse() return out
python
def make_call_positionals(stack_builders, count): """ Make the args entry for an ast.Call node. """ out = [make_expr(stack_builders) for _ in range(count)] out.reverse() return out
Make the args entry for an ast.Call node.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1061-L1067
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_exprs
def make_exprs(stack_builders, count): """ Make elements of set/list/tuple literal. """ exprs = [make_expr(stack_builders) for _ in range(count)] # Elements are on the stack from right to left, but we want them from right # to left. exprs.reverse() return exprs
python
def make_exprs(stack_builders, count): """ Make elements of set/list/tuple literal. """ exprs = [make_expr(stack_builders) for _ in range(count)] # Elements are on the stack from right to left, but we want them from right # to left. exprs.reverse() return exprs
Make elements of set/list/tuple literal.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1094-L1102
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_make_expr_empty_dict
def _make_expr_empty_dict(toplevel, stack_builders): """ This should only be hit for empty dicts. Anything else should hit the STORE_MAP handler instead. """ if toplevel.arg: raise DecompilationError( "make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg ) ...
python
def _make_expr_empty_dict(toplevel, stack_builders): """ This should only be hit for empty dicts. Anything else should hit the STORE_MAP handler instead. """ if toplevel.arg: raise DecompilationError( "make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg ) ...
This should only be hit for empty dicts. Anything else should hit the STORE_MAP handler instead.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1106-L1120
llllllllll/codetransformer
codetransformer/decompiler/_343.py
find_build_map
def find_build_map(stack_builders): """ Find the BUILD_MAP instruction for which the last element of ``stack_builders`` is a store. """ assert isinstance(stack_builders[-1], instrs.STORE_MAP) to_consume = 0 for instr in reversed(stack_builders): if isinstance(instr, instrs.STORE_MAP...
python
def find_build_map(stack_builders): """ Find the BUILD_MAP instruction for which the last element of ``stack_builders`` is a store. """ assert isinstance(stack_builders[-1], instrs.STORE_MAP) to_consume = 0 for instr in reversed(stack_builders): if isinstance(instr, instrs.STORE_MAP...
Find the BUILD_MAP instruction for which the last element of ``stack_builders`` is a store.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1143-L1162
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_make_dict_elems
def _make_dict_elems(build_instr, builders): """ Return a list of keys and a list of values for the dictionary literal generated by ``build_instr``. """ keys = [] values = [] for _ in range(build_instr.arg): popped = builders.pop() if not isinstance(popped, instrs.STORE_MAP):...
python
def _make_dict_elems(build_instr, builders): """ Return a list of keys and a list of values for the dictionary literal generated by ``build_instr``. """ keys = [] values = [] for _ in range(build_instr.arg): popped = builders.pop() if not isinstance(popped, instrs.STORE_MAP):...
Return a list of keys and a list of values for the dictionary literal generated by ``build_instr``.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1165-L1186
llllllllll/codetransformer
codetransformer/decompiler/_343.py
normalize_tuple_slice
def normalize_tuple_slice(node): """ Normalize an ast.Tuple node representing the internals of a slice. Returns the node wrapped in an ast.Index. Returns an ExtSlice node built from the tuple elements if there are any slices. """ if not any(isinstance(elt, ast.Slice) for elt in node.elts): ...
python
def normalize_tuple_slice(node): """ Normalize an ast.Tuple node representing the internals of a slice. Returns the node wrapped in an ast.Index. Returns an ExtSlice node built from the tuple elements if there are any slices. """ if not any(isinstance(elt, ast.Slice) for elt in node.elts): ...
Normalize an ast.Tuple node representing the internals of a slice. Returns the node wrapped in an ast.Index. Returns an ExtSlice node built from the tuple elements if there are any slices.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1244-L1261
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_binop_handler
def _binop_handler(nodetype): """ Factory function for binary operator handlers. """ def _handler(toplevel, stack_builders): right = make_expr(stack_builders) left = make_expr(stack_builders) return ast.BinOp(left=left, op=nodetype(), right=right) return _handler
python
def _binop_handler(nodetype): """ Factory function for binary operator handlers. """ def _handler(toplevel, stack_builders): right = make_expr(stack_builders) left = make_expr(stack_builders) return ast.BinOp(left=left, op=nodetype(), right=right) return _handler
Factory function for binary operator handlers.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1344-L1352
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_function
def make_function(function_builders, *, closure): """ Construct a FunctionDef AST node from a sequence of the form: LOAD_CLOSURE, N times (when handling MAKE_CLOSURE) BUILD_TUPLE(N) (when handling MAKE_CLOSURE) <decorator builders> (optional) <default builders>, (optional) <annotation build...
python
def make_function(function_builders, *, closure): """ Construct a FunctionDef AST node from a sequence of the form: LOAD_CLOSURE, N times (when handling MAKE_CLOSURE) BUILD_TUPLE(N) (when handling MAKE_CLOSURE) <decorator builders> (optional) <default builders>, (optional) <annotation build...
Construct a FunctionDef AST node from a sequence of the form: LOAD_CLOSURE, N times (when handling MAKE_CLOSURE) BUILD_TUPLE(N) (when handling MAKE_CLOSURE) <decorator builders> (optional) <default builders>, (optional) <annotation builders> (optional) LOAD_CONST(<tuple of annotated names>) (op...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1360-L1430
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_function_arguments
def make_function_arguments(args, kwonly, varargs, varkwargs, defaults, kw_defaults, annotations): """ Make an ast.arguments from the args parse...
python
def make_function_arguments(args, kwonly, varargs, varkwargs, defaults, kw_defaults, annotations): """ Make an ast.arguments from the args parse...
Make an ast.arguments from the args parsed out of a code object.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1433-L1456
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_global_and_nonlocal_decls
def make_global_and_nonlocal_decls(code_instrs): """ Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations. """ globals_ = sorted(set( i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOB...
python
def make_global_and_nonlocal_decls(code_instrs): """ Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations. """ globals_ = sorted(set( i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOB...
Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1469-L1487
llllllllll/codetransformer
codetransformer/decompiler/_343.py
make_defaults_and_annotations
def make_defaults_and_annotations(make_function_instr, builders): """ Get the AST expressions corresponding to the defaults, kwonly defaults, and annotations for a function created by `make_function_instr`. """ # Integer counts. n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_...
python
def make_defaults_and_annotations(make_function_instr, builders): """ Get the AST expressions corresponding to the defaults, kwonly defaults, and annotations for a function created by `make_function_instr`. """ # Integer counts. n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_...
Get the AST expressions corresponding to the defaults, kwonly defaults, and annotations for a function created by `make_function_instr`.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1490-L1527
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_check_make_function_instrs
def _check_make_function_instrs(load_code_instr, load_name_instr, make_function_instr, *, expect_lambda=False): """ Validate the instructions passed to a make_function call. """ ...
python
def _check_make_function_instrs(load_code_instr, load_name_instr, make_function_instr, *, expect_lambda=False): """ Validate the instructions passed to a make_function call. """ ...
Validate the instructions passed to a make_function call.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1550-L1601
llllllllll/codetransformer
codetransformer/decompiler/_343.py
pop_arguments
def pop_arguments(instr, stack): """ Pop instructions off `stack` until we pop all instructions that will produce values popped by `instr`. """ needed = instr.stack_effect if needed >= 0: raise DecompilationError( "%s is does not have a negative stack effect" % instr ...
python
def pop_arguments(instr, stack): """ Pop instructions off `stack` until we pop all instructions that will produce values popped by `instr`. """ needed = instr.stack_effect if needed >= 0: raise DecompilationError( "%s is does not have a negative stack effect" % instr ...
Pop instructions off `stack` until we pop all instructions that will produce values popped by `instr`.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1604-L1627
llllllllll/codetransformer
codetransformer/decompiler/_343.py
_check_stack_for_module_return
def _check_stack_for_module_return(stack): """ Verify that the stack is in the expected state before the dummy RETURN_VALUE instruction of a module or class. """ fail = ( len(stack) != 1 or not isinstance(stack[0], instrs.LOAD_CONST) or stack[0].arg is not None ) if ...
python
def _check_stack_for_module_return(stack): """ Verify that the stack is in the expected state before the dummy RETURN_VALUE instruction of a module or class. """ fail = ( len(stack) != 1 or not isinstance(stack[0], instrs.LOAD_CONST) or stack[0].arg is not None ) if ...
Verify that the stack is in the expected state before the dummy RETURN_VALUE instruction of a module or class.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1630-L1645
llllllllll/codetransformer
codetransformer/decompiler/_343.py
expect
def expect(instr, expected, context): """ Check that an instruction is of the expected type. """ if not isinstance(instr, expected): raise DecompilationError( "Expected a {expected} instruction {context}. Got {instr}.".format( instr=instr, expected=expected, context=c...
python
def expect(instr, expected, context): """ Check that an instruction is of the expected type. """ if not isinstance(instr, expected): raise DecompilationError( "Expected a {expected} instruction {context}. Got {instr}.".format( instr=instr, expected=expected, context=c...
Check that an instruction is of the expected type.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1648-L1658
llllllllll/codetransformer
codetransformer/decompiler/_343.py
popwhile
def popwhile(cond, queue, *, side): """ Pop elements off a queue while `cond(nextelem)` is True. Parameters ---------- cond : predicate queue : deque side : {'left', 'right'} Returns ------- popped : deque Examples -------- >>> from collections import deque >>>...
python
def popwhile(cond, queue, *, side): """ Pop elements off a queue while `cond(nextelem)` is True. Parameters ---------- cond : predicate queue : deque side : {'left', 'right'} Returns ------- popped : deque Examples -------- >>> from collections import deque >>>...
Pop elements off a queue while `cond(nextelem)` is True. Parameters ---------- cond : predicate queue : deque side : {'left', 'right'} Returns ------- popped : deque Examples -------- >>> from collections import deque >>> d = deque([1, 2, 3, 2, 1]) >>> popwhile(lam...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/_343.py#L1668-L1713
llllllllll/codetransformer
codetransformer/transformers/literals.py
overloaded_constants
def overloaded_constants(type_, __doc__=None): """A factory for transformers that apply functions to literals. Parameters ---------- type_ : type The type to overload. __doc__ : str, optional Docstring for the generated transformer. Returns ------- transformer : subclas...
python
def overloaded_constants(type_, __doc__=None): """A factory for transformers that apply functions to literals. Parameters ---------- type_ : type The type to overload. __doc__ : str, optional Docstring for the generated transformer. Returns ------- transformer : subclas...
A factory for transformers that apply functions to literals. Parameters ---------- type_ : type The type to overload. __doc__ : str, optional Docstring for the generated transformer. Returns ------- transformer : subclass of CodeTransformer A new code transformer cl...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/literals.py#L237-L268
llllllllll/codetransformer
codetransformer/transformers/literals.py
overloaded_build
def overloaded_build(type_, add_name=None): """Factory for constant transformers that apply to a given build instruction. Parameters ---------- type_ : type The object type to overload the construction of. This must be one of "buildable" types, or types with a "BUILD_*" instruction....
python
def overloaded_build(type_, add_name=None): """Factory for constant transformers that apply to a given build instruction. Parameters ---------- type_ : type The object type to overload the construction of. This must be one of "buildable" types, or types with a "BUILD_*" instruction....
Factory for constant transformers that apply to a given build instruction. Parameters ---------- type_ : type The object type to overload the construction of. This must be one of "buildable" types, or types with a "BUILD_*" instruction. add_name : str, optional The suffix of...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/literals.py#L350-L411
llllllllll/codetransformer
codetransformer/decompiler/__init__.py
paramnames
def paramnames(co): """ Get the parameter names from a pycode object. Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs). varargs and varkwargs will be None if the function doesn't take *args or **kwargs, respectively. """ flags = co.co_flags varnames = co.co_varnames argc...
python
def paramnames(co): """ Get the parameter names from a pycode object. Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs). varargs and varkwargs will be None if the function doesn't take *args or **kwargs, respectively. """ flags = co.co_flags varnames = co.co_varnames argc...
Get the parameter names from a pycode object. Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs). varargs and varkwargs will be None if the function doesn't take *args or **kwargs, respectively.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/decompiler/__init__.py#L6-L29
llllllllll/codetransformer
codetransformer/code.py
_freevar_argname
def _freevar_argname(arg, cellvars, freevars): """ Get the name of the variable manipulated by a 'uses_free' instruction. Parameters ---------- arg : int The raw argument to a uses_free instruction that we want to resolve to a name. cellvars : list[str] The co_cellvars o...
python
def _freevar_argname(arg, cellvars, freevars): """ Get the name of the variable manipulated by a 'uses_free' instruction. Parameters ---------- arg : int The raw argument to a uses_free instruction that we want to resolve to a name. cellvars : list[str] The co_cellvars o...
Get the name of the variable manipulated by a 'uses_free' instruction. Parameters ---------- arg : int The raw argument to a uses_free instruction that we want to resolve to a name. cellvars : list[str] The co_cellvars of the function for which we want to resolve `arg`. free...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L193-L217
llllllllll/codetransformer
codetransformer/code.py
pycode
def pycode(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab, freevars=(), cellvars=())...
python
def pycode(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab, freevars=(), cellvars=())...
types.CodeType constructor that accepts keyword arguments. See Also -------- types.CodeType
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L220-L257
llllllllll/codetransformer
codetransformer/code.py
Code.from_pycode
def from_pycode(cls, co): """Create a Code object from a python code object. Parameters ---------- co : CodeType The python code object. Returns ------- code : Code The codetransformer Code object. """ # Make it sparse to ...
python
def from_pycode(cls, co): """Create a Code object from a python code object. Parameters ---------- co : CodeType The python code object. Returns ------- code : Code The codetransformer Code object. """ # Make it sparse to ...
Create a Code object from a python code object. Parameters ---------- co : CodeType The python code object. Returns ------- code : Code The codetransformer Code object.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L429-L510
llllllllll/codetransformer
codetransformer/code.py
Code.to_pycode
def to_pycode(self): """Create a python code object from the more abstract codetransfomer.Code object. Returns ------- co : CodeType The python code object. """ consts = self.consts names = self.names varnames = self.varnames f...
python
def to_pycode(self): """Create a python code object from the more abstract codetransfomer.Code object. Returns ------- co : CodeType The python code object. """ consts = self.consts names = self.names varnames = self.varnames f...
Create a python code object from the more abstract codetransfomer.Code object. Returns ------- co : CodeType The python code object.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L512-L600
llllllllll/codetransformer
codetransformer/code.py
Code.consts
def consts(self): """The constants referenced in this code object. """ # We cannot use a set comprehension because consts do not need # to be hashable. consts = [] append_const = consts.append for instr in self.instrs: if isinstance(instr, LOAD_CONST) ...
python
def consts(self): """The constants referenced in this code object. """ # We cannot use a set comprehension because consts do not need # to be hashable. consts = [] append_const = consts.append for instr in self.instrs: if isinstance(instr, LOAD_CONST) ...
The constants referenced in this code object.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L634-L644
llllllllll/codetransformer
codetransformer/code.py
Code.names
def names(self): """The names referenced in this code object. Names come from instructions like LOAD_GLOBAL or STORE_ATTR where the name of the global or attribute is needed at runtime. """ # We must sort to preserve the order between calls. # The set comprehension is to...
python
def names(self): """The names referenced in this code object. Names come from instructions like LOAD_GLOBAL or STORE_ATTR where the name of the global or attribute is needed at runtime. """ # We must sort to preserve the order between calls. # The set comprehension is to...
The names referenced in this code object. Names come from instructions like LOAD_GLOBAL or STORE_ATTR where the name of the global or attribute is needed at runtime.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L647-L657
llllllllll/codetransformer
codetransformer/code.py
Code.varnames
def varnames(self): """The names of all of the local variables in this code object. """ # We must sort to preserve the order between calls. # The set comprehension is to drop the duplicates. return self._argnames + tuple(sorted({ instr.arg for instr in sel...
python
def varnames(self): """The names of all of the local variables in this code object. """ # We must sort to preserve the order between calls. # The set comprehension is to drop the duplicates. return self._argnames + tuple(sorted({ instr.arg for instr in sel...
The names of all of the local variables in this code object.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L669-L678
llllllllll/codetransformer
codetransformer/code.py
Code.py_lnotab
def py_lnotab(self): """The encoded lnotab that python uses to compute when lines start. Note ---- See Objects/lnotab_notes.txt in the cpython source for more details. """ reverse_lnotab = reverse_dict(self.lnotab) py_lnotab = [] prev_instr = 0 pr...
python
def py_lnotab(self): """The encoded lnotab that python uses to compute when lines start. Note ---- See Objects/lnotab_notes.txt in the cpython source for more details. """ reverse_lnotab = reverse_dict(self.lnotab) py_lnotab = [] prev_instr = 0 pr...
The encoded lnotab that python uses to compute when lines start. Note ---- See Objects/lnotab_notes.txt in the cpython source for more details.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L783-L811
llllllllll/codetransformer
codetransformer/code.py
Code.stacksize
def stacksize(self): """The maximum amount of stack space used by this code object. """ return max(scanl( op.add, 0, map(op.attrgetter('stack_effect'), self.instrs), ))
python
def stacksize(self): """The maximum amount of stack space used by this code object. """ return max(scanl( op.add, 0, map(op.attrgetter('stack_effect'), self.instrs), ))
The maximum amount of stack space used by this code object.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L814-L821
llllllllll/codetransformer
codetransformer/utils/immutable.py
initialize_slot
def initialize_slot(obj, name, value): """Initalize an unitialized slot to a value. If there is already a value for this slot, this is a nop. Parameters ---------- obj : immutable An immutable object. name : str The name of the slot to initialize. value : any The va...
python
def initialize_slot(obj, name, value): """Initalize an unitialized slot to a value. If there is already a value for this slot, this is a nop. Parameters ---------- obj : immutable An immutable object. name : str The name of the slot to initialize. value : any The va...
Initalize an unitialized slot to a value. If there is already a value for this slot, this is a nop. Parameters ---------- obj : immutable An immutable object. name : str The name of the slot to initialize. value : any The value to initialize the slot to.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L61-L76
llllllllll/codetransformer
codetransformer/utils/immutable.py
_create_init
def _create_init(name, slots, defaults): """Create the __init__ function for an immutable object. Parameters ---------- name : str The name of the immutable class. slots : iterable of str The __slots__ field from the class. defaults : dict or None The default values for ...
python
def _create_init(name, slots, defaults): """Create the __init__ function for an immutable object. Parameters ---------- name : str The name of the immutable class. slots : iterable of str The __slots__ field from the class. defaults : dict or None The default values for ...
Create the __init__ function for an immutable object. Parameters ---------- name : str The name of the immutable class. slots : iterable of str The __slots__ field from the class. defaults : dict or None The default values for the arguments to __init__. Returns ----...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L79-L174
llllllllll/codetransformer
codetransformer/utils/immutable.py
_wrapinit
def _wrapinit(init): """Wrap an existing initialize function by thawing self for the duration of the init. Parameters ---------- init : callable The user-provided init. Returns ------- wrapped : callable The wrapped init method. """ try: spec = getfullar...
python
def _wrapinit(init): """Wrap an existing initialize function by thawing self for the duration of the init. Parameters ---------- init : callable The user-provided init. Returns ------- wrapped : callable The wrapped init method. """ try: spec = getfullar...
Wrap an existing initialize function by thawing self for the duration of the init. Parameters ---------- init : callable The user-provided init. Returns ------- wrapped : callable The wrapped init method.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L177-L261
llllllllll/codetransformer
codetransformer/utils/immutable.py
_check_missing_slots
def _check_missing_slots(ob): """Check that all slots have been initialized when a custom __init__ method is provided. Parameters ---------- ob : immutable The instance that was just initialized. Raises ------ TypeError Raised when the instance has not set values that a...
python
def _check_missing_slots(ob): """Check that all slots have been initialized when a custom __init__ method is provided. Parameters ---------- ob : immutable The instance that was just initialized. Raises ------ TypeError Raised when the instance has not set values that a...
Check that all slots have been initialized when a custom __init__ method is provided. Parameters ---------- ob : immutable The instance that was just initialized. Raises ------ TypeError Raised when the instance has not set values that are named in the __slots__.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/immutable.py#L264-L287
llllllllll/codetransformer
codetransformer/utils/functional.py
scanl
def scanl(f, n, ns): """Reduce ns by f starting with n yielding each intermediate value. tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n) Parameters ---------- f : callable A binary function. n : any The starting value. ns : iterable of any The iterable to scan over. ...
python
def scanl(f, n, ns): """Reduce ns by f starting with n yielding each intermediate value. tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n) Parameters ---------- f : callable A binary function. n : any The starting value. ns : iterable of any The iterable to scan over. ...
Reduce ns by f starting with n yielding each intermediate value. tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n) Parameters ---------- f : callable A binary function. n : any The starting value. ns : iterable of any The iterable to scan over. Yields ------ p...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/functional.py#L21-L49
llllllllll/codetransformer
codetransformer/utils/functional.py
ffill
def ffill(iterable): """Forward fill non None values in some iterable. Parameters ---------- iterable : iterable The iterable to forward fill. Yields ------ e : any The last non None value or None if there has not been a non None value. """ it = iter(iterable) p...
python
def ffill(iterable): """Forward fill non None values in some iterable. Parameters ---------- iterable : iterable The iterable to forward fill. Yields ------ e : any The last non None value or None if there has not been a non None value. """ it = iter(iterable) p...
Forward fill non None values in some iterable. Parameters ---------- iterable : iterable The iterable to forward fill. Yields ------ e : any The last non None value or None if there has not been a non None value.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/functional.py#L75-L96
llllllllll/codetransformer
codetransformer/utils/functional.py
flatten
def flatten(seq, *, recurse_types=(tuple, list, set, frozenset)): """ Convert a (possibly nested) iterator into a flattened iterator. Parameters ---------- seq : iterable The sequence to flatten. recurse_types, optional Types to recursively flatten. Defaults to (tuple, l...
python
def flatten(seq, *, recurse_types=(tuple, list, set, frozenset)): """ Convert a (possibly nested) iterator into a flattened iterator. Parameters ---------- seq : iterable The sequence to flatten. recurse_types, optional Types to recursively flatten. Defaults to (tuple, l...
Convert a (possibly nested) iterator into a flattened iterator. Parameters ---------- seq : iterable The sequence to flatten. recurse_types, optional Types to recursively flatten. Defaults to (tuple, list, set, frozenset). >>> list(flatten((1, (2, 3), ((4,), 5)))) [1, 2...
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/utils/functional.py#L99-L121
llllllllll/codetransformer
codetransformer/transformers/interpolated_strings.py
interpolated_strings.types
def types(self): """ Tuple containing types transformed by this transformer. """ out = [] if self._transform_bytes: out.append(bytes) if self._transform_str: out.append(str) return tuple(out)
python
def types(self): """ Tuple containing types transformed by this transformer. """ out = [] if self._transform_bytes: out.append(bytes) if self._transform_str: out.append(str) return tuple(out)
Tuple containing types transformed by this transformer.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L55-L64
llllllllll/codetransformer
codetransformer/transformers/interpolated_strings.py
interpolated_strings._transform_constant_sequence
def _transform_constant_sequence(self, seq): """ Transform a frozenset or tuple. """ should_transform = is_a(self.types) if not any(filter(should_transform, flatten(seq))): # Tuple doesn't contain any transformable strings. Ignore. yield LOAD_CONST(seq) ...
python
def _transform_constant_sequence(self, seq): """ Transform a frozenset or tuple. """ should_transform = is_a(self.types) if not any(filter(should_transform, flatten(seq))): # Tuple doesn't contain any transformable strings. Ignore. yield LOAD_CONST(seq) ...
Transform a frozenset or tuple.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L81-L107