language
stringclasses 1
value | repo
stringclasses 346
values | path
stringlengths 6
201
| class_span
dict | source
stringlengths 21
2.38M
| target
stringlengths 1
96
|
|---|---|---|---|---|---|
python
|
fluentpython__example-code-2e
|
10-dp-1class-func/strategy_param.py
|
{
"start": 1178,
"end": 1247
}
|
class ____(typing.NamedTuple):
name: str
fidelity: int
|
Customer
|
python
|
python-poetry__poetry
|
src/poetry/repositories/link_sources/json.py
|
{
"start": 364,
"end": 1850
}
|
class ____(LinkSource):
"""Links as returned by PEP 691 compatible JSON-based Simple API."""
def __init__(self, url: str, content: dict[str, Any]) -> None:
super().__init__(url=url)
self.content = content
@cached_property
def _link_cache(self) -> LinkCache:
links: LinkCache = defaultdict(lambda: defaultdict(list))
for file in self.content["files"]:
url = file["url"]
requires_python = file.get("requires-python")
yanked = file.get("yanked", False)
# see https://peps.python.org/pep-0714/#clients
# and https://peps.python.org/pep-0691/#project-detail
metadata: dict[str, str] | bool = False
for metadata_key in ("core-metadata", "dist-info-metadata"):
if metadata_key in file:
metadata_value = file[metadata_key]
if metadata_value and isinstance(metadata_value, dict):
metadata = metadata_value
else:
metadata = bool(metadata_value)
break
link = Link(
url, requires_python=requires_python, yanked=yanked, metadata=metadata
)
if link.ext not in self.SUPPORTED_FORMATS:
continue
pkg = self.link_package_data(link)
if pkg:
links[pkg.name][pkg.version].append(link)
return links
|
SimpleJsonPage
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/storage/local_compute_log_manager.py
|
{
"start": 1255,
"end": 9251
}
|
class ____(ComputeLogManager, ConfigurableClass):
"""Stores copies of stdout & stderr for each compute step locally on disk."""
def __init__(
self,
base_dir: str,
polling_timeout: Optional[float] = None,
inst_data: Optional[ConfigurableClassData] = None,
):
self._base_dir = base_dir
self._polling_timeout = check.opt_float_param(
polling_timeout, "polling_timeout", DEFAULT_WATCHDOG_POLLING_TIMEOUT
)
self._subscription_manager = LocalComputeLogSubscriptionManager(self)
self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData)
@property
def inst_data(self) -> Optional[ConfigurableClassData]:
return self._inst_data
@property
def polling_timeout(self) -> float:
return self._polling_timeout
@classmethod
def config_type(cls) -> UserConfigSchema:
return {
"base_dir": StringSource,
"polling_timeout": Field(Float, is_required=False),
}
@classmethod
def from_config_value(
cls, inst_data: Optional[ConfigurableClassData], config_value
) -> "LocalComputeLogManager":
return LocalComputeLogManager(inst_data=inst_data, **config_value)
@contextmanager
def capture_logs(self, log_key: Sequence[str]) -> Generator[CapturedLogContext, None, None]:
outpath = self.get_captured_local_path(log_key, IO_TYPE_EXTENSION[ComputeIOType.STDOUT])
errpath = self.get_captured_local_path(log_key, IO_TYPE_EXTENSION[ComputeIOType.STDERR])
with mirror_stream_to_file(sys.stdout, outpath), mirror_stream_to_file(sys.stderr, errpath):
yield CapturedLogContext(log_key)
# leave artifact on filesystem so that we know the capture is completed
touch_file(self.complete_artifact_path(log_key))
@contextmanager
def open_log_stream(
self, log_key: Sequence[str], io_type: ComputeIOType
) -> Iterator[Optional[IO]]:
path = self.get_captured_local_path(log_key, IO_TYPE_EXTENSION[io_type])
ensure_file(path)
with open(path, "+a", encoding="utf-8") as f:
yield f
def is_capture_complete(self, log_key: Sequence[str]) -> bool:
return os.path.exists(self.complete_artifact_path(log_key))
def get_log_data(
self, log_key: Sequence[str], cursor: Optional[str] = None, max_bytes: Optional[int] = None
) -> CapturedLogData:
stdout_cursor, stderr_cursor = self.parse_cursor(cursor)
stdout, stdout_offset = self.get_log_data_for_type(
log_key, ComputeIOType.STDOUT, offset=stdout_cursor, max_bytes=max_bytes
)
stderr, stderr_offset = self.get_log_data_for_type(
log_key, ComputeIOType.STDERR, offset=stderr_cursor, max_bytes=max_bytes
)
return CapturedLogData(
log_key=log_key,
stdout=stdout,
stderr=stderr,
cursor=self.build_cursor(stdout_offset, stderr_offset),
)
def get_log_metadata(self, log_key: Sequence[str]) -> CapturedLogMetadata:
return CapturedLogMetadata(
stdout_location=self.get_captured_local_path(
log_key, IO_TYPE_EXTENSION[ComputeIOType.STDOUT]
),
stderr_location=self.get_captured_local_path(
log_key, IO_TYPE_EXTENSION[ComputeIOType.STDERR]
),
stdout_download_url=self.get_captured_log_download_url(log_key, ComputeIOType.STDOUT),
stderr_download_url=self.get_captured_log_download_url(log_key, ComputeIOType.STDERR),
)
def delete_logs(
self, log_key: Optional[Sequence[str]] = None, prefix: Optional[Sequence[str]] = None
):
if log_key:
paths = [
self.get_captured_local_path(log_key, IO_TYPE_EXTENSION[ComputeIOType.STDOUT]),
self.get_captured_local_path(log_key, IO_TYPE_EXTENSION[ComputeIOType.STDERR]),
self.get_captured_local_path(
log_key, IO_TYPE_EXTENSION[ComputeIOType.STDOUT], partial=True
),
self.get_captured_local_path(
log_key, IO_TYPE_EXTENSION[ComputeIOType.STDERR], partial=True
),
self.get_captured_local_path(log_key, "complete"),
]
for path in paths:
if os.path.exists(path) and os.path.isfile(path):
os.remove(path)
elif prefix:
dir_to_delete = os.path.join(self._base_dir, *prefix)
if os.path.exists(dir_to_delete) and os.path.isdir(dir_to_delete):
# recursively delete all files in dir
shutil.rmtree(dir_to_delete)
else:
check.failed("Must pass in either `log_key` or `prefix` argument to delete_logs")
def get_log_data_for_type(
self,
log_key: Sequence[str],
io_type: ComputeIOType,
offset: Optional[int] = 0,
max_bytes: Optional[int] = None,
):
path = self.get_captured_local_path(log_key, IO_TYPE_EXTENSION[io_type])
return self.read_path(path, offset or 0, max_bytes)
def complete_artifact_path(self, log_key):
return self.get_captured_local_path(log_key, "complete")
def read_path(
self,
path: str,
offset: int = 0,
max_bytes: Optional[int] = None,
):
if not os.path.exists(path) or not os.path.isfile(path):
return None, offset
with open(path, "rb") as f:
f.seek(offset, os.SEEK_SET)
if max_bytes is None:
data = f.read()
else:
data = f.read(max_bytes)
new_offset = f.tell()
return data, new_offset
def get_captured_log_download_url(self, log_key, io_type):
check.inst_param(io_type, "io_type", ComputeIOType)
url = "/logs"
for part in log_key:
url = f"{url}/{part}"
return f"{url}/{IO_TYPE_EXTENSION[io_type]}"
def get_captured_local_path(self, log_key: Sequence[str], extension: str, partial=False):
[*namespace, filebase] = log_key
filename = f"{filebase}.{extension}"
if partial:
filename = f"{filename}.partial"
if len(filename) > MAX_FILENAME_LENGTH:
filename = "{}.{}".format(non_secure_md5_hash_str(filebase.encode("utf-8")), extension)
base_dir_path = Path(self._base_dir).resolve()
log_path = base_dir_path.joinpath(*namespace, filename).resolve()
if base_dir_path not in log_path.parents:
raise ValueError("Invalid path")
return str(log_path)
def subscribe(
self, log_key: Sequence[str], cursor: Optional[str] = None
) -> CapturedLogSubscription:
subscription = CapturedLogSubscription(self, log_key, cursor)
self._subscription_manager.add_subscription(subscription)
return subscription
def unsubscribe(self, subscription):
self._subscription_manager.remove_subscription(subscription)
def get_log_keys_for_log_key_prefix(
self, log_key_prefix: Sequence[str], io_type: ComputeIOType
) -> Sequence[Sequence[str]]:
"""Returns the logs keys for a given log key prefix. This is determined by looking at the
directory defined by the log key prefix and creating a log_key for each file in the directory.
"""
base_dir_path = Path(self._base_dir).resolve()
directory = base_dir_path.joinpath(*log_key_prefix)
objects = directory.iterdir()
results = []
list_key_prefix = list(log_key_prefix)
for obj in objects:
if obj.is_file() and obj.suffix == "." + IO_TYPE_EXTENSION[io_type]:
results.append(list_key_prefix + [obj.stem])
return results
def dispose(self) -> None:
self._subscription_manager.dispose()
|
LocalComputeLogManager
|
python
|
django__django
|
tests/db_functions/json/test_json_object.py
|
{
"start": 3371,
"end": 3653
}
|
class ____(TestCase):
def test_not_supported(self):
msg = "JSONObject() is not supported on this database backend."
with self.assertRaisesMessage(NotSupportedError, msg):
Author.objects.annotate(json_object=JSONObject()).get()
|
JSONObjectNotSupportedTests
|
python
|
huggingface__transformers
|
src/transformers/models/flava/modeling_flava.py
|
{
"start": 36567,
"end": 40589
}
|
class ____(FlavaPreTrainedModel):
config: FlavaTextConfig
# This override allows us to load FlavaTextModel from FlavaModel/FlavaForPreTraining checkpoints.
base_model_prefix = "flava.text_model"
input_modalities = ("text",)
def __init__(self, config: FlavaTextConfig, add_pooling_layer: bool = True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
self.embeddings = FlavaTextEmbeddings(config)
self.encoder = FlavaEncoder(config)
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.pooler = FlavaPooler(config) if add_pooling_layer else None
self.post_init()
def get_input_embeddings(self) -> PatchEmbeddings:
return self.embeddings.word_embeddings
def set_input_embeddings(self, value: nn.Module):
self.embeddings.word_embeddings = value
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutputWithPooling]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, text_seq_length)`):
Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
[`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
IDs?](../glossary#input-ids)
token_type_ids (`torch.LongTensor` of shape `(batch_size, text_seq_length)`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is None:
raise ValueError("You have to specify input_ids")
input_shape = input_ids.size()
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=input_ids.device)
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
attention_mask, input_shape, input_ids.device
)
embedding_output = self.embeddings(
input_ids=input_ids,
token_type_ids=token_type_ids,
position_ids=position_ids,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
sequence_output = self.layernorm(sequence_output)
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@auto_docstring
|
FlavaTextModel
|
python
|
Netflix__metaflow
|
metaflow/plugins/cards/card_decorator.py
|
{
"start": 736,
"end": 1332
}
|
class ____(object):
def __init__(self, info_func):
self._info_func = info_func
self._metadata_registered = {}
def register_metadata(self, card_uuid) -> Tuple[bool, Dict]:
info = self._info_func()
# Check that metadata was not written yet. We only want to write once.
if (
info is None
or info.get(card_uuid) is None
or self._metadata_registered.get(card_uuid)
):
return False, {}
self._metadata_registered[card_uuid] = True
return True, info.get(card_uuid)
|
MetadataStateManager
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
|
{
"start": 22690,
"end": 22906
}
|
class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("CHEVRON_UP", "DOT", "DOT_FILL", "HEART_FILL", "PLUS", "ZAP")
|
PinnedDiscussionPattern
|
python
|
redis__redis-py
|
tests/test_connection.py
|
{
"start": 13579,
"end": 20064
}
|
class ____:
def test_clears_cache_on_disconnect(self, mock_connection, cache_conf):
cache = DefaultCache(CacheConfig(max_size=10))
cache_key = CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
)
cache.set(
CacheEntry(
cache_key=cache_key,
cache_value=b"bar",
status=CacheEntryStatus.VALID,
connection_ref=mock_connection,
)
)
assert cache.get(cache_key).cache_value == b"bar"
mock_connection.disconnect.return_value = None
mock_connection.retry = "mock"
mock_connection.host = "mock"
mock_connection.port = "mock"
mock_connection.credential_provider = UsernamePasswordCredentialProvider()
proxy_connection = CacheProxyConnection(
mock_connection, cache, threading.RLock()
)
proxy_connection.disconnect()
assert len(cache.collection) == 0
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="Pypy doesn't support side_effect",
)
def test_read_response_returns_cached_reply(self, mock_cache, mock_connection):
mock_connection.retry = "mock"
mock_connection.host = "mock"
mock_connection.port = "mock"
mock_connection.credential_provider = UsernamePasswordCredentialProvider()
mock_cache.is_cachable.return_value = True
mock_cache.get.side_effect = [
None,
None,
CacheEntry(
cache_key=CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
),
cache_value=CacheProxyConnection.DUMMY_CACHE_VALUE,
status=CacheEntryStatus.IN_PROGRESS,
connection_ref=mock_connection,
),
CacheEntry(
cache_key=CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
),
cache_value=b"bar",
status=CacheEntryStatus.VALID,
connection_ref=mock_connection,
),
CacheEntry(
cache_key=CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
),
cache_value=b"bar",
status=CacheEntryStatus.VALID,
connection_ref=mock_connection,
),
CacheEntry(
cache_key=CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
),
cache_value=b"bar",
status=CacheEntryStatus.VALID,
connection_ref=mock_connection,
),
]
mock_connection.send_command.return_value = Any
mock_connection.read_response.return_value = b"bar"
mock_connection.can_read.return_value = False
proxy_connection = CacheProxyConnection(
mock_connection, mock_cache, threading.RLock()
)
proxy_connection.send_command(*["GET", "foo"], **{"keys": ["foo"]})
assert proxy_connection.read_response() == b"bar"
assert proxy_connection._current_command_cache_key is None
assert proxy_connection.read_response() == b"bar"
mock_cache.set.assert_has_calls(
[
call(
CacheEntry(
cache_key=CacheKey(
command="GET",
redis_keys=("foo",),
redis_args=("GET", "foo"),
),
cache_value=CacheProxyConnection.DUMMY_CACHE_VALUE,
status=CacheEntryStatus.IN_PROGRESS,
connection_ref=mock_connection,
)
),
call(
CacheEntry(
cache_key=CacheKey(
command="GET",
redis_keys=("foo",),
redis_args=("GET", "foo"),
),
cache_value=b"bar",
status=CacheEntryStatus.VALID,
connection_ref=mock_connection,
)
),
]
)
mock_cache.get.assert_has_calls(
[
call(
CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
)
),
call(
CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
)
),
call(
CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
)
),
]
)
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="Pypy doesn't support side_effect",
)
def test_triggers_invalidation_processing_on_another_connection(
self, mock_cache, mock_connection
):
mock_connection.retry = "mock"
mock_connection.host = "mock"
mock_connection.port = "mock"
mock_connection.credential_provider = UsernamePasswordCredentialProvider()
another_conn = copy.deepcopy(mock_connection)
another_conn.can_read.side_effect = [True, False]
another_conn.read_response.return_value = None
cache_entry = CacheEntry(
cache_key=CacheKey(
command="GET", redis_keys=("foo",), redis_args=("GET", "foo")
),
cache_value=b"bar",
status=CacheEntryStatus.VALID,
connection_ref=another_conn,
)
mock_cache.is_cachable.return_value = True
mock_cache.get.return_value = cache_entry
mock_connection.can_read.return_value = False
proxy_connection = CacheProxyConnection(
mock_connection, mock_cache, threading.RLock()
)
proxy_connection.send_command(*["GET", "foo"], **{"keys": ["foo"]})
assert proxy_connection.read_response() == b"bar"
assert another_conn.can_read.call_count == 2
another_conn.read_response.assert_called_once()
|
TestUnitCacheProxyConnection
|
python
|
tensorflow__tensorflow
|
tensorflow/python/autograph/pyct/transpiler_test.py
|
{
"start": 1415,
"end": 5421
}
|
class ____(test.TestCase):
def test_basic(self):
def f(a):
return a + 1
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 0)
def test_closure(self):
b = 1
def f(a):
return a + b
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 0)
b = 2
self.assertEqual(f(1), -1)
def test_global(self):
def f(a):
return a + global_var_for_test_global
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
global global_var_for_test_global
global_var_for_test_global = 1
self.assertEqual(f(1), 0)
global_var_for_test_global = 2
self.assertEqual(f(1), -1)
def test_defaults(self):
b = 2
c = 1
def f(a, d=c + 1):
return a + b + d
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 1 - 2 - 2)
c = 0
self.assertEqual(f(1), 1 - 2 - 2) # Defaults are evaluated at definition.
b = 1
self.assertEqual(f(1), 1 - 2 - 1)
def test_call_tree(self):
def g(a):
return a + 1
def f(a):
return g(a) + 1
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 1 - 1 + 1) # Only f is converted.
def test_lambda(self):
b = 2
f = lambda x: (b + (x if x > 0 else -x))
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 2 - 1)
self.assertEqual(f(-1), 2 - 1)
b = 3
self.assertEqual(f(1), 3 - 1)
self.assertEqual(f(-1), 3 - 1)
def test_multiple_lambdas(self):
a, b = 1, 2
# This can be disambiguated by the argument names.
f, _ = (lambda x: a + x, lambda y: b * y)
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 1 - 1)
def test_nested_functions(self):
b = 2
def f(x):
def g(x):
return b + x
return g(x)
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 2 - 1)
def test_nested_lambda(self):
b = 2
def f(x):
g = lambda x: b + x
return g(x)
tr = TestTranspiler()
f, _, _ = tr.transform(f, None)
self.assertEqual(f(1), 2 - 1)
def test_concurrency(self):
def f():
pass
outputs = []
tr = TestTranspiler()
# Note: this is not a test, it's a required invariant.
assert tr.get_caching_key(None) == tr.get_caching_key(None)
def conversion_thread():
_, mod, _ = tr.transform(f, None)
outputs.append(mod.__name__)
threads = tuple(
threading.Thread(target=conversion_thread) for _ in range(10))
for t in threads:
t.start()
for t in threads:
t.join()
# Races would potentially create multiple functions / modules
# (non-deterministically, but with high likelihood).
self.assertEqual(len(set(outputs)), 1)
def test_reentrance(self):
def test_fn():
return 1 + 1
class ReentrantTranspiler(transpiler.PyToPy):
def __init__(self):
super(ReentrantTranspiler, self).__init__()
self._recursion_depth = 0
def get_caching_key(self, ctx):
del ctx
return 0
def get_extra_locals(self):
return {}
def transform_ast(self, node, ctx):
self._recursion_depth += 1
if self._recursion_depth < 2:
self.transform(test_fn, None)
return FlipSignTransformer(ctx).visit(node)
tr = ReentrantTranspiler()
f, _, _ = tr.transform(test_fn, None)
self.assertEqual(f(), 0)
def test_namespace_collisions_avoided(self):
class TestClass(object):
def global_var_for_test_namespace_collisions(self):
return global_var_for_test_namespace_collisions
tr = TestTranspiler()
obj = TestClass()
f, _, _ = tr.transform(
obj.global_var_for_test_namespace_collisions, None)
self.assertIs(f(obj), global_var_for_test_namespace_collisions)
if __name__ == '__main__':
test.main()
|
PyToPyTest
|
python
|
pyca__cryptography
|
src/cryptography/hazmat/primitives/ciphers/algorithms.py
|
{
"start": 3229,
"end": 3496
}
|
class ____(BlockCipherAlgorithm):
name = "SM4"
block_size = 128
key_sizes = frozenset([128])
def __init__(self, key: bytes):
self.key = _verify_key_size(self, key)
@property
def key_size(self) -> int:
return len(self.key) * 8
|
SM4
|
python
|
doocs__leetcode
|
solution/0500-0599/0519.Random Flip Matrix/Solution.py
|
{
"start": 0,
"end": 593
}
|
class ____:
def __init__(self, m: int, n: int):
self.m = m
self.n = n
self.total = m * n
self.mp = {}
def flip(self) -> List[int]:
self.total -= 1
x = random.randint(0, self.total)
idx = self.mp.get(x, x)
self.mp[x] = self.mp.get(self.total, self.total)
return [idx // self.n, idx % self.n]
def reset(self) -> None:
self.total = self.m * self.n
self.mp.clear()
# Your Solution object will be instantiated and called as such:
# obj = Solution(m, n)
# param_1 = obj.flip()
# obj.reset()
|
Solution
|
python
|
numba__numba
|
numba/core/types/containers.py
|
{
"start": 547,
"end": 1255
}
|
class ____(Type):
"""
A heterogeneous pair.
"""
def __init__(self, first_type, second_type):
self.first_type = first_type
self.second_type = second_type
name = "pair<%s, %s>" % (first_type, second_type)
super(Pair, self).__init__(name=name)
@property
def key(self):
return self.first_type, self.second_type
def unify(self, typingctx, other):
if isinstance(other, Pair):
first = typingctx.unify_pairs(self.first_type, other.first_type)
second = typingctx.unify_pairs(self.second_type, other.second_type)
if first is not None and second is not None:
return Pair(first, second)
|
Pair
|
python
|
weaviate__weaviate-python-client
|
weaviate/collections/classes/types.py
|
{
"start": 298,
"end": 379
}
|
class ____(BaseModel):
model_config = ConfigDict(extra="forbid")
|
_WeaviateInput
|
python
|
django__django
|
tests/admin_widgets/widgetadmin.py
|
{
"start": 405,
"end": 746
}
|
class ____(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return db_field.formfield(**kwargs)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
|
CarTireAdmin
|
python
|
huggingface__transformers
|
src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py
|
{
"start": 6993,
"end": 7599
}
|
class ____(GraniteMoeSharedPreTrainedModel):
config: GraniteMoeHybridConfig
_no_split_modules = ["GraniteMoeHybridDecoderLayer"]
_is_stateful = True
@torch.no_grad()
def _init_weights(self, module):
super()._init_weights(module)
if isinstance(module, GraniteMoeHybridMambaLayer):
init.ones_(module.dt_bias)
init.copy_(module.A_log, torch.log(torch.arange(1, module.num_heads + 1)))
init.ones_(module.D)
elif isinstance(module, GraniteMoeHybridRMSNormGated):
init.ones_(module.weight)
|
GraniteMoeHybridPreTrainedModel
|
python
|
huggingface__transformers
|
src/transformers/models/perceiver/modeling_perceiver.py
|
{
"start": 112728,
"end": 113422
}
|
class ____(nn.Module):
"""
Classification postprocessing for Perceiver. Can be used to convert the decoder output to classification logits.
Args:
config ([*PerceiverConfig*]):
Model configuration.
in_channels (`int`):
Number of channels in the input.
"""
def __init__(self, config: PerceiverConfig, in_channels: int) -> None:
super().__init__()
self.classifier = nn.Linear(in_channels, config.num_labels)
def forward(self, inputs, pos: Optional[torch.Tensor] = None, modality_sizes=None) -> torch.Tensor:
logits = self.classifier(inputs)
return logits[:, 0, :]
|
PerceiverClassificationPostprocessor
|
python
|
scipy__scipy
|
scipy/optimize/_trustregion_constr/report.py
|
{
"start": 1066,
"end": 1410
}
|
class ____(ReportBase):
COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
"opt", "c viol", "penalty", "CG stop"]
COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7]
ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
"^10.2e", "^10.2e", "^7"]
|
SQPReport
|
python
|
dask__distributed
|
distributed/recreate_tasks.py
|
{
"start": 271,
"end": 1276
}
|
class ____:
"""A plugin for the scheduler to recreate tasks locally
This adds the following routes to the scheduler
* get_runspec
* get_error_cause
"""
def __init__(self, scheduler):
self.scheduler = scheduler
self.scheduler.handlers["get_runspec"] = self.get_runspec
self.scheduler.handlers["get_error_cause"] = self.get_error_cause
def _process_key(self, key):
if isinstance(key, list):
key = tuple(key) # ensure not a list from msgpack
return key
def get_error_cause(self, *args, keys=(), **kwargs):
for key in keys:
key = self._process_key(key)
ts = self.scheduler.tasks.get(key)
if ts is not None and ts.exception_blame is not None:
return ts.exception_blame.key
def get_runspec(self, *args, key=None, **kwargs):
key = self._process_key(key)
ts = self.scheduler.tasks[key]
return ToPickle(ts.run_spec)
|
ReplayTaskScheduler
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_20/tasks.py
|
{
"start": 357637,
"end": 361207
}
|
class ____(Response):
"""
Response of tasks.publish_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "publish_many"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"failed": {
"items": {
"properties": {
"error": {
"description": "Error info",
"properties": {
"codes": {
"items": {"type": "integer"},
"type": "array",
},
"data": {
"additionalProperties": True,
"type": "object",
},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {
"description": "ID of the failed entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"succeeded": {
"items": {
"properties": {
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": "object",
},
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": "integer",
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(
self, succeeded: Optional[List[dict]] = None, failed: Optional[List[dict]] = None, **kwargs: Any
) -> None:
super(PublishManyResponse, self).__init__(**kwargs)
self.succeeded = succeeded
self.failed = failed
@schema_property("succeeded")
def succeeded(self) -> Optional[List[dict]]:
return self._property_succeeded
@succeeded.setter
def succeeded(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_succeeded = None
return
self.assert_isinstance(value, "succeeded", (list, tuple))
self.assert_isinstance(value, "succeeded", (dict,), is_array=True)
self._property_succeeded = value
@schema_property("failed")
def failed(self) -> Optional[List[dict]]:
return self._property_failed
@failed.setter
def failed(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_failed = None
return
self.assert_isinstance(value, "failed", (list, tuple))
self.assert_isinstance(value, "failed", (dict,), is_array=True)
self._property_failed = value
|
PublishManyResponse
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
|
{
"start": 223066,
"end": 225323
}
|
class ____(GeneratedAirbyteSource):
class PasswordAuthentication:
@public
def __init__(self, auth_user_password: str):
self.auth_method = "SSH_PASSWORD_AUTH"
self.auth_user_password = check.str_param(auth_user_password, "auth_user_password")
class SSHKeyAuthentication:
@public
def __init__(self, auth_ssh_key: str):
self.auth_method = "SSH_KEY_AUTH"
self.auth_ssh_key = check.str_param(auth_ssh_key, "auth_ssh_key")
@public
def __init__(
self,
name: str,
user: str,
host: str,
port: int,
credentials: Union["SftpSource.PasswordAuthentication", "SftpSource.SSHKeyAuthentication"],
file_types: Optional[str] = None,
folder_path: Optional[str] = None,
file_pattern: Optional[str] = None,
):
"""Airbyte Source for Sftp.
Documentation can be found at https://docs.airbyte.com/integrations/sources/sftp
Args:
name (str): The name of the destination.
user (str): The server user
host (str): The server host address
port (int): The server port
credentials (Union[SftpSource.PasswordAuthentication, SftpSource.SSHKeyAuthentication]): The server authentication method
file_types (Optional[str]): Coma separated file types. Currently only 'csv' and 'json' types are supported.
folder_path (Optional[str]): The directory to search files for sync
file_pattern (Optional[str]): The regular expression to specify files for sync in a chosen Folder Path
"""
self.user = check.str_param(user, "user")
self.host = check.str_param(host, "host")
self.port = check.int_param(port, "port")
self.credentials = check.inst_param(
credentials,
"credentials",
(SftpSource.PasswordAuthentication, SftpSource.SSHKeyAuthentication),
)
self.file_types = check.opt_str_param(file_types, "file_types")
self.folder_path = check.opt_str_param(folder_path, "folder_path")
self.file_pattern = check.opt_str_param(file_pattern, "file_pattern")
super().__init__("Sftp", name)
|
SftpSource
|
python
|
ray-project__ray
|
rllib/models/torch/torch_action_dist.py
|
{
"start": 14530,
"end": 16818
}
|
class ____(TorchDistributionWrapper):
"""
A Beta distribution is defined on the interval [0, 1] and parameterized by
shape parameters alpha and beta (also called concentration parameters).
PDF(x; alpha, beta) = x**(alpha - 1) (1 - x)**(beta - 1) / Z
with Z = Gamma(alpha) Gamma(beta) / Gamma(alpha + beta)
and Gamma(n) = (n - 1)!
"""
def __init__(
self,
inputs: List[TensorType],
model: TorchModelV2,
low: float = 0.0,
high: float = 1.0,
):
super().__init__(inputs, model)
# Stabilize input parameters (possibly coming from a linear layer).
self.inputs = torch.clamp(self.inputs, log(SMALL_NUMBER), -log(SMALL_NUMBER))
self.inputs = torch.log(torch.exp(self.inputs) + 1.0) + 1.0
self.low = low
self.high = high
alpha, beta = torch.chunk(self.inputs, 2, dim=-1)
# Note: concentration0==beta, concentration1=alpha (!)
self.dist = torch.distributions.Beta(concentration1=alpha, concentration0=beta)
@override(ActionDistribution)
def deterministic_sample(self) -> TensorType:
self.last_sample = self._squash(self.dist.mean)
return self.last_sample
@override(TorchDistributionWrapper)
def sample(self) -> TensorType:
# Use the reparameterization version of `dist.sample` to allow for
# the results to be backprop'able e.g. in a loss term.
normal_sample = self.dist.rsample()
self.last_sample = self._squash(normal_sample)
return self.last_sample
@override(ActionDistribution)
def logp(self, x: TensorType) -> TensorType:
unsquashed_values = self._unsquash(x)
return torch.sum(self.dist.log_prob(unsquashed_values), dim=-1)
def _squash(self, raw_values: TensorType) -> TensorType:
return raw_values * (self.high - self.low) + self.low
def _unsquash(self, values: TensorType) -> TensorType:
return (values - self.low) / (self.high - self.low)
@staticmethod
@override(ActionDistribution)
def required_model_output_shape(
action_space: gym.Space, model_config: ModelConfigDict
) -> Union[int, np.ndarray]:
return np.prod(action_space.shape, dtype=np.int32) * 2
@OldAPIStack
|
TorchBeta
|
python
|
PyCQA__pydocstyle
|
src/tests/test_cases/test.py
|
{
"start": 3680,
"end": 3963
}
|
class ____:
"""TrailingSpace."""
pass
expect('LeadingAndTrailingSpaceMissing',
'D203: 1 blank line required before class docstring (found 0)')
expect('LeadingAndTrailingSpaceMissing',
'D204: 1 blank line required after class docstring (found 0)')
|
TrailingSpace
|
python
|
django__django
|
tests/reverse_lookup/models.py
|
{
"start": 326,
"end": 581
}
|
class ____(models.Model):
name = models.CharField(max_length=100)
poll = models.ForeignKey(Poll, models.CASCADE, related_name="poll_choice")
related_poll = models.ForeignKey(
Poll, models.CASCADE, related_name="related_choice"
)
|
Choice
|
python
|
pytorch__pytorch
|
test/distributed/test_nvshmem.py
|
{
"start": 9088,
"end": 26262
}
|
class ____(MultiProcContinuousTest):
def _init_device(self) -> None:
# TODO: relieve this (seems to hang if without)
device_module.set_device(self.device)
# Set NVSHMEM as SymmMem backend
symm_mem.set_backend("NVSHMEM")
@property
def device(self) -> torch.device:
return torch.device(device_type, self.rank)
@skipIfRocm
def test_nvshmem_all_to_all(self) -> None:
self._init_device()
group_name = dist.group.WORLD.group_name
symm_mem.enable_symm_mem_for_group(group_name)
dtype = torch.float
numel_per_peer = 10
numel = self.world_size * numel_per_peer
inp = symm_mem.empty(numel, dtype=dtype, device=self.device).fill_(self.rank)
out = symm_mem.empty(numel, dtype=dtype, device=self.device).fill_(-1)
symm_mem.rendezvous(inp, group=group_name)
symm_mem.rendezvous(out, group=group_name)
torch.ops.symm_mem.nvshmem_all_to_all(inp, out, group_name)
expected = torch.cat(
[
torch.empty(numel_per_peer, dtype=dtype, device=self.device).fill_(i)
for i in range(self.world_size)
]
)
torch.testing.assert_close(out, expected)
@skipIfRocm
def test_all_to_all_vdev(self) -> None:
self._init_device()
group_name = dist.group.WORLD.group_name
symm_mem.enable_symm_mem_for_group(group_name)
dtype = torch.float
# Number of elements for a peer is random between [0, k)
k = 10
inp_splits = torch.randint(k, (self.world_size,), device=self.device)
inp_numel = inp_splits.sum().item()
# Exchange input splits to get output splits
out_splits = torch.zeros_like(inp_splits)
dist.all_to_all_single(out_splits, inp_splits)
out_numel = out_splits.sum().item()
# Max number of input elements (must be a constant across ranks for symmetric memory allocation)
max_inp_numel = k * self.world_size
# Max number of output elements (must be a constant across ranks for symmetric memory allocation)
overflow_factor = self.world_size # worst case: one rank receives all data
max_out_numel = max_inp_numel * overflow_factor
inp = symm_mem.empty(max_inp_numel, dtype=dtype, device=self.device).copy_(
torch.randn(max_inp_numel, dtype=dtype, device=self.device)
)
out = symm_mem.empty(max_out_numel, dtype=dtype, device=self.device).fill_(-1)
in_splits = symm_mem.empty(
self.world_size, dtype=torch.int64, device=self.device
)
out_splits_offsets = symm_mem.empty(
(2, self.world_size), dtype=torch.int64, device=self.device
)
# Row 0 is input splits
in_splits.copy_(inp_splits)
# Sync all ranks to ensure remote tensors are allocated
dist.barrier()
torch.ops.symm_mem.all_to_all_vdev(
inp, out, in_splits, out_splits_offsets, group_name
)
# Check input splits (row 0) -- should not change
torch.testing.assert_close(in_splits, inp_splits)
# Check output splits (row 1)
torch.testing.assert_close(out_splits_offsets[0], out_splits)
# Check output offsets (row 2)
out_offsets = torch.cumsum(out_splits, dim=0) # inclusive scan
# output offsets from `all_to_all_vdev` is exclusive scan
self.assertEqual(out_splits_offsets[1][0], 0)
torch.testing.assert_close(out_splits_offsets[1][1:], out_offsets[:-1])
# Check data
expected = torch.empty(out_numel, dtype=dtype, device=self.device)
dist.all_to_all_single(
expected, inp[:inp_numel], out_splits.tolist(), inp_splits.tolist()
)
torch.testing.assert_close(out[:out_numel], expected)
@skipIfRocm
@parametrize("align", [1, 8, 16]) # `major_align` of output
def test_all_to_all_vdev_2d(self, align: int) -> None:
torch.manual_seed(42 + self.rank)
self._init_device()
group_name = dist.group.WORLD.group_name
symm_mem.enable_symm_mem_for_group(group_name)
dtype = torch.float
# Number of experts per rank
ne = 8
nsplits = ne * self.world_size
# Number of elements for an expert is random between [0, k)
k = 10
inp_splits = torch.randint(k, (nsplits,), dtype=torch.int64, device=self.device)
# Exchange input splits to get output splits
out_splits = torch.zeros_like(inp_splits)
dist.all_to_all_single(out_splits, inp_splits)
# We do a .t() here because there is a rank-major to expert-major shuffle
out_splits_t = out_splits.reshape(self.world_size, ne).t()
# Actual number of input elements
inp_numel = inp_splits.sum().item()
# Actual number of output elements
out_numel = out_splits.sum().item()
# Max number of input elements (must be a constant across ranks for symmetric memory allocation)
max_inp_numel = k * nsplits
# Max number of output elements (must be a constant across ranks for symmetric memory allocation)
overflow_factor = self.world_size # worst case: one rank receives all data
max_out_numel = max_inp_numel * overflow_factor
inp = symm_mem.empty(max_inp_numel, dtype=dtype, device=self.device).copy_(
torch.randn(max_inp_numel, dtype=dtype, device=self.device)
)
out = symm_mem.empty(max_out_numel, dtype=dtype, device=self.device).fill_(-1)
in_splits = symm_mem.empty(
nsplits, dtype=torch.int64, device=self.device
).copy_(inp_splits)
# 2 rows: output splits, output offsets
# Initializing all values to -1 to check if they are updated
out_splits_offsets = symm_mem.empty(
(2, nsplits), dtype=torch.int64, device=self.device
).fill_(-1)
# Sync all ranks to ensure remote tensors are allocated
dist.barrier()
torch.ops.symm_mem.all_to_all_vdev_2d(
inp, out, in_splits, out_splits_offsets, group_name, major_align=align
)
received_out_splits = out_splits_offsets[0]
received_out_offsets = out_splits_offsets[1]
# Check input splits (row 0) -- should not change
torch.testing.assert_close(in_splits, inp_splits)
# Check output splits (row 1)
torch.testing.assert_close(received_out_splits, out_splits_t.reshape(-1))
# Check output offsets (row 2)
out_split_list = out_splits_t.tolist()
for i in range(ne):
expert_sum = 0
for j in range(self.world_size):
expert_sum += out_split_list[i][j]
# Align up expert_sum
expert_sum_aligned = (expert_sum + align - 1) // align * align
# If 0, make it at least `align` (bc cutlass currently does not support empty bins)
expert_sum_aligned = max(expert_sum_aligned, align)
# last element absorbs the padding
out_split_list[i][-1] += expert_sum_aligned - expert_sum
out_splits_padded = torch.tensor(out_split_list, device=self.device).reshape(-1)
out_offsets = torch.cumsum(out_splits_padded, dim=0) # inclusive scan
# Make it exclusive scan because that's what `all_to_all_vdev_2d` returns
out_offsets = torch.cat(
[torch.zeros(1, device=self.device), out_offsets[:-1]]
).to(torch.int64)
torch.testing.assert_close(received_out_offsets, out_offsets)
# Check data
expected = torch.empty(out_numel, dtype=dtype, device=self.device)
inp_splits_rank = inp_splits.reshape(self.world_size, ne).sum(1)
out_splits_rank = out_splits.reshape(self.world_size, ne).sum(1)
dist.all_to_all_single(
expected,
inp[:inp_numel],
out_splits_rank.tolist(),
inp_splits_rank.tolist(),
)
# We still need to shuffle `expected`
out_offsets = torch.cumsum(out_splits, dim=0) # inclusive scan
result_list = []
for j in range(ne):
for i in range(self.world_size):
chunk_id = i * ne + j
offset = out_offsets[chunk_id]
chunk = expected[offset - out_splits[chunk_id] : offset]
result_list.append(chunk)
# Do a chunk-wise comparison
for c, chunk in enumerate(result_list):
start = received_out_offsets[c].item()
split = received_out_splits[c].item()
received_chunk = out[start : start + split]
torch.testing.assert_close(received_chunk, chunk)
@skipIfRocm
def test_all_to_all_vdev_2d_offset(self) -> None:
torch.manual_seed(42 + self.rank)
self._init_device()
group_name = dist.group.WORLD.group_name
symm_mem.enable_symm_mem_for_group(group_name)
dtype = torch.float
# Number of experts per rank
ne = 8
nsplits = ne * self.world_size
# Number of elements for an expert is random between [0, k)
k = 10
inp_splits = torch.randint(k, (nsplits,), dtype=torch.int64, device=self.device)
# Each split up align to k, as the offset, i.e. [0, k, 2k, 3k, ...]
inp_offsets = torch.arange(
0, k * nsplits, k, dtype=torch.int64, device=self.device
)
# Max number of input elements (must be a constant across ranks for symmetric memory allocation)
# Remember that we up-align each input split to k?
max_inp_numel = k * nsplits
# Max number of output elements (must be a constant across ranks for symmetric memory allocation)
overflow_factor = self.world_size # worst case: one rank receives all data
max_out_numel = max_inp_numel * overflow_factor
inp = symm_mem.empty(max_inp_numel, dtype=dtype, device=self.device).copy_(
torch.randn(max_inp_numel, dtype=dtype, device=self.device)
)
out = symm_mem.empty(max_out_numel, dtype=dtype, device=self.device).fill_(-1)
# 2 rows: input splits, input offsets
in_splits_offsets = symm_mem.empty(
(2, nsplits), dtype=torch.int64, device=self.device
)
# 2 rows: output splits, output offsets
# Initializing all values to -1 to check if they are updated
out_splits_offsets = symm_mem.empty(
(2, nsplits), dtype=torch.int64, device=self.device
).fill_(-1)
# Row 0 is input splits
in_splits_offsets[0].copy_(inp_splits)
# Row 1 is input offsets
in_splits_offsets[1].copy_(inp_offsets)
# Sync all ranks to ensure remote tensors are allocated
dist.barrier()
torch.ops.symm_mem.all_to_all_vdev_2d_offset(
inp, out, in_splits_offsets, out_splits_offsets, group_name
)
received_out_splits = out_splits_offsets[0]
received_out_offsets = out_splits_offsets[1]
# Check input splits and offsets -- should not change
torch.testing.assert_close(in_splits_offsets[0], inp_splits)
torch.testing.assert_close(in_splits_offsets[1], inp_offsets)
# Check output splits (row 1)
# Exchange input splits to get output splits
out_splits = torch.zeros_like(inp_splits)
# First need to transpose the input splits
inp_splits_t = inp_splits.reshape(ne, self.world_size).t().contiguous()
dist.all_to_all_single(out_splits, inp_splits_t)
torch.testing.assert_close(received_out_splits, out_splits)
# Check output offsets (row 2)
out_offsets = torch.cumsum(out_splits, dim=0) # inclusive scan
# output offsets from `all_to_all_vdev_2d_offset` is exclusive scan
self.assertEqual(received_out_offsets[0], 0)
torch.testing.assert_close(received_out_offsets[1:], out_offsets[:-1])
# Check data
# Let's "squeeze" the padding out of the input data first
inp_chunks = [] # (ne, nranks)
for i in range(ne):
inp_chunks_e = [] # (nranks,)
for j in range(self.world_size):
chunk_id = i * self.world_size + j
offset = in_splits_offsets[1][chunk_id]
chunk = inp[offset : offset + inp_splits[chunk_id]]
inp_chunks_e.append(chunk)
inp_chunks.append(inp_chunks_e)
# Transpose the 2D input chunks
inp_chunks_t = list(zip(*inp_chunks))
# Now it is (nranks, ne), concatenate the e's
inp_chunks_t = [torch.cat(row) for row in inp_chunks_t]
# Create empty output tensors -- each tensor is data to be received from a peer
out_splits = out_splits.reshape(self.world_size, ne)
# Sum the split sizes of all experts, per peer
receive_size_per_peer = out_splits.sum(1)
out_chunks = [] # (nranks,)
for i in range(self.world_size):
out_chunks.append(
torch.empty(
receive_size_per_peer[i].item(), dtype=dtype, device=self.device
)
)
# All-to-all
dist.all_to_all(out_chunks, inp_chunks_t)
# Concatenate the output chunks received from all peers
out_expected = torch.cat(out_chunks)
# Actual number of output elements
out_numel = out_splits.sum().item()
self.assertEqual(out_expected.shape[0], out_numel)
# Check data
torch.testing.assert_close(out_expected, out[:out_numel])
# Help function used by multiple tests
def dispatch_then_combine(device, align: int, group) -> None:
"""
Shuffle the tokens, then combine them, and check if the combined data is
exactly the same as the original input data
"""
group_name = group.group_name
symm_mem.enable_symm_mem_for_group(group_name)
dtype = torch.float
# Number of experts per rank
ne = 8
nsplits = ne * group.size()
# Number of elements for an expert is random between [0, k)
k = 10
inp_splits = torch.randint(k, (nsplits,), dtype=torch.int64, device=device)
# Actual number of input elements
inp_numel = inp_splits.sum().item()
# Max number of input elements (must be a constant across ranks for symmetric memory allocation)
max_inp_numel = k * nsplits
# Max number of output elements (must be a constant across ranks for symmetric memory allocation)
overflow_factor = group.size() # worst case: one rank receives all data
max_out_numel = max_inp_numel * overflow_factor
# Buffers for shuffle
inp = symm_mem.empty(max_inp_numel, dtype=dtype, device=device).copy_(
torch.randn(max_inp_numel, dtype=dtype, device=device)
)
out = symm_mem.empty(max_out_numel, dtype=dtype, device=device).fill_(-1)
in_splits = symm_mem.empty(nsplits, dtype=torch.int64, device=device).copy_(
inp_splits
)
# 2 rows: output splits, output offsets
# Initializing all values to -1 to check if they are updated
out_splits_offsets = symm_mem.empty(
(2, nsplits), dtype=torch.int64, device=device
).fill_(-1)
# Buffers for combine
combine_out = symm_mem.empty(max_out_numel, dtype=dtype, device=device).fill_(-1)
# 2 rows: output splits, output offsets
# Initializing all values to -1 to check if they are updated
combine_out_splits_offsets = symm_mem.empty(
(2, nsplits), dtype=torch.int64, device=device
).fill_(-1)
# Wait for all ranks to finish tensor allocation before accessing them
torch.cuda.synchronize(device)
dist.barrier(group=group)
# Shuffle the tokens
torch.ops.symm_mem.all_to_all_vdev_2d(
inp, out, in_splits, out_splits_offsets, group_name, major_align=align
)
# Combine the tokens
# `out_splits_offsets` from shuffle is exactly the `input_splits_offsets` for combine
# `out` data from shuffle is exactly the `input` data for combine
torch.ops.symm_mem.all_to_all_vdev_2d_offset(
out, combine_out, out_splits_offsets, combine_out_splits_offsets, group_name
)
# Assert the combined data is exactly the same as the original input data
torch.testing.assert_close(combine_out[:inp_numel], inp[:inp_numel])
# Assert the combined out splits are exactly the same as the original input splits
torch.testing.assert_close(combine_out_splits_offsets[0], inp_splits)
# Assert the combined out offsets are exactly the same as the original input offsets
inp_offsets = torch.cumsum(inp_splits, dim=0) # inclusive scan
# Make it exclusive scan because that's what `all_to_all_vdev_2d_offset` returns
inp_offsets = torch.cat([torch.zeros(1, device=device), inp_offsets[:-1]]).to(
torch.int64
)
torch.testing.assert_close(combine_out_splits_offsets[1], inp_offsets)
# Wait for all ranks to finish accessing tensors before freeing them
dist.barrier(group=group)
torch.cuda.synchronize(device)
@instantiate_parametrized_tests
@requires_nvshmem()
@requires_cuda_p2p_access()
|
NVSHMEMAll2AllTest
|
python
|
pennersr__django-allauth
|
allauth/socialaccount/forms.py
|
{
"start": 1205,
"end": 2037
}
|
class ____(forms.Form):
account = forms.ModelChoiceField(
queryset=SocialAccount.objects.none(),
widget=forms.RadioSelect,
required=True,
)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
self.accounts = SocialAccount.objects.filter(user=self.request.user)
super(DisconnectForm, self).__init__(*args, **kwargs)
self.fields["account"].queryset = self.accounts
def clean(self):
cleaned_data = super(DisconnectForm, self).clean()
account = cleaned_data.get("account")
if account:
flows.connect.validate_disconnect(self.request, account)
return cleaned_data
def save(self):
account = self.cleaned_data["account"]
flows.connect.disconnect(self.request, account)
|
DisconnectForm
|
python
|
django__django
|
tests/db_functions/text/test_sha512.py
|
{
"start": 228,
"end": 2367
}
|
class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
[
Author(alias="John Smith"),
Author(alias="Jordan Élena"),
Author(alias="皇帝"),
Author(alias=""),
Author(alias=None),
]
)
def test_basic(self):
authors = (
Author.objects.annotate(
sha512_alias=SHA512("alias"),
)
.values_list("sha512_alias", flat=True)
.order_by("pk")
)
self.assertSequenceEqual(
authors,
[
"ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd803f33cf"
"3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055efff040a3fc091518",
"b09c449f3ba49a32ab44754982d4749ac938af293e4af2de28858858080a1611"
"2b719514b5e48cb6ce54687e843a4b3e69a04cdb2a9dc99c3b99bdee419fa7d0",
"b554d182e25fb487a3f2b4285bb8672f98956b5369138e681b467d1f079af116"
"172d88798345a3a7666faf5f35a144c60812d3234dcd35f444624f2faee16857",
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
(
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
if connection.features.interprets_empty_strings_as_nulls
else None
),
],
)
def test_transform(self):
with register_lookup(CharField, SHA512):
authors = Author.objects.filter(
alias__sha512=(
"ed014a19bb67a85f9c8b1d81e04a0e7101725be8627d79d02ca4f3bd8"
"03f33cf3b8fed53e80d2a12c0d0e426824d99d110f0919298a5055eff"
"f040a3fc091518"
),
).values_list("alias", flat=True)
self.assertSequenceEqual(authors, ["John Smith"])
|
SHA512Tests
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/definitions/metadata/metadata_set.py
|
{
"start": 3980,
"end": 6150
}
|
class ____(NamespacedKVSet):
"""Extend this class to define a set of metadata fields in the same namespace.
Supports splatting to a dictionary that can be placed inside a metadata argument along with
other dictionary-structured metadata.
.. code-block:: python
my_metadata: NamespacedMetadataSet = ...
return MaterializeResult(metadata={**my_metadata, ...})
"""
def __init__(self, *args, **kwargs) -> None:
for field_name in model_fields(self.__class__).keys():
annotation_types = self._get_accepted_types_for_field(field_name)
invalid_annotation_types = {
annotation_type
for annotation_type in annotation_types
if not is_raw_metadata_type(annotation_type)
}
if invalid_annotation_types:
check.failed(
f"Type annotation for field '{field_name}' includes invalid metadata type(s): {invalid_annotation_types}"
)
super().__init__(*args, **kwargs)
@classmethod
def _extract_value(cls, field_name: str, value: Any) -> Any:
"""Based on type annotation, potentially coerce the metadata value to its inner value.
E.g. if the annotation is Optional[float] and the value is FloatMetadataValue, construct
the MetadataSet using the inner float.
"""
if isinstance(value, MetadataValue):
annotation = model_fields(cls)[field_name].annotation
annotation_acceptable_types = flatten_unions(annotation)
if (
type(value) not in annotation_acceptable_types
and type(value.value) in annotation_acceptable_types
):
check.invariant(type(value.value) in DIRECTLY_WRAPPED_METADATA_TYPES)
return value.value
return value
@classmethod
@cache # this avoids wastefully recomputing this once per instance
def _get_accepted_types_for_field(cls, field_name: str) -> AbstractSet[type]:
annotation = model_fields(cls)[field_name].annotation
return flatten_unions(annotation)
|
NamespacedMetadataSet
|
python
|
falconry__falcon
|
examples/recipes/raw_url_path_asgi.py
|
{
"start": 39,
"end": 383
}
|
class ____:
async def process_request(self, req, resp):
raw_path = req.scope.get('raw_path')
# NOTE: Decode the raw path from the raw_path bytestring, disallowing
# non-ASCII characters, assuming they are correctly percent-coded.
if raw_path:
req.path = raw_path.decode('ascii')
|
RawPathComponent
|
python
|
getsentry__sentry
|
src/sentry/web/frontend/debug/debug_new_release_email.py
|
{
"start": 725,
"end": 5089
}
|
class ____(View):
def get(self, request: HttpRequest) -> HttpResponse:
org = Organization(id=1, slug="organization", name="My Company")
projects = [
Project(id=1, organization=org, slug="project", name="My Project"),
Project(id=2, organization=org, slug="another-project", name="Another Project"),
Project(id=3, organization=org, slug="yet-another-project", name="Yet Another Project"),
]
version = "6c998f755f304593a4713abd123eaf8833a2de5e"
version_parsed = parse_release(version)["description"]
release = Release(
organization_id=org.id,
version=version,
date_added=datetime.datetime(2016, 10, 12, 15, 39, tzinfo=timezone.utc),
)
deploy = Deploy(
release=release,
organization_id=org.id,
environment_id=1,
date_finished=datetime.datetime(2016, 10, 12, 15, 39, tzinfo=timezone.utc),
)
release_links = [
absolute_uri(f"/organizations/{org.slug}/releases/{release.version}/?project={p.id}")
for p in projects
]
repos = [
{
"name": "getsentry/getsentry",
"commits": [
(
Commit(
key="48b86fcd677da3dba5679d7a738240ce6fb74b20",
date_added=datetime.datetime(2016, 10, 11, 15, 39, tzinfo=timezone.utc),
),
None,
),
(
Commit(
key="a53a2756bb8d111b43196210b34df90b87ed336b",
message="Fix billing",
author=CommitAuthor(name="David Cramer", email="david@sentry.io"),
date_added=datetime.datetime(2016, 10, 11, 16, 45, tzinfo=timezone.utc),
),
User(email="david@sentry.io", name="David Cramer"),
),
],
},
{
"name": "getsentry/sentry",
"commits": [
(
Commit(
key="3c8eb3b4af6ee2a29c68daa188fc730c8e4b39fd",
date_added=datetime.datetime(2016, 10, 10, 15, 39, tzinfo=timezone.utc),
),
None,
),
(
Commit(
key="373562702009df1692da6eb80a933139f29e094b",
message="Fix padding",
author=CommitAuthor(name="Chris Jennings", email="chris@sentry.io"),
date_added=datetime.datetime(2016, 10, 10, 16, 39, tzinfo=timezone.utc),
),
None,
),
(
Commit(
key="631cd9096bd9811a046a472bb0aa8b573e86e1f1",
message="Update README.rst",
author=CommitAuthor(name="David Cramer", email="david@sentry.io"),
date_added=datetime.datetime(2016, 10, 11, 10, 39, tzinfo=timezone.utc),
),
User(email="david@sentry.io", name="David Cramer"),
),
],
},
]
return MailPreview(
html_template="sentry/emails/activity/release.html",
text_template="sentry/emails/activity/release.txt",
context={
"author_count": 1,
"commit_count": 4,
"deploy": deploy,
"environment": "production",
"file_count": 5,
"project_count": len(projects),
"projects": list(zip(projects, release_links, [6, 1, 0])),
"reason": GroupSubscriptionReason.descriptions[GroupSubscriptionReason.committed],
"release": release,
"repos": repos,
"setup_repo_link": absolute_uri(f"/organizations/{org.slug}/repos/"),
"version_parsed": version_parsed,
},
).render(request)
|
DebugNewReleaseEmailView
|
python
|
readthedocs__readthedocs.org
|
readthedocs/projects/migrations/0091_upate_meta_options.py
|
{
"start": 120,
"end": 448
}
|
class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0090_dont_allow_ips_on_domains"),
]
operations = [
migrations.AlterModelOptions(
name="project",
options={"ordering": ("slug",), "verbose_name": "project"},
),
]
|
Migration
|
python
|
google__jax
|
jax/_src/buffer_callback.py
|
{
"start": 7583,
"end": 10463
}
|
class ____(effects.Effect):
def __str__(self):
return "BufferCallback"
_BufferCallbackEffect = BufferCallbackEffect()
effects.lowerable_effects.add_type(BufferCallbackEffect)
effects.control_flow_allowed_effects.add_type(BufferCallbackEffect)
@buffer_callback_p.def_effectful_abstract_eval
def _buffer_callback_abstract_eval(
*args,
result_avals: tuple[core.ShapedArray, ...],
has_side_effect: bool,
**_,
):
del args
effects = {_BufferCallbackEffect} if has_side_effect else core.no_effects
return result_avals, effects
def _buffer_callback_jvp_rule(*args, **kwargs):
del args, kwargs
raise ValueError(
"Buffer callbacks do not support JVP. "
"Please use `jax.custom_jvp` to use callbacks while taking gradients.")
ad.primitive_jvps[buffer_callback_p] = _buffer_callback_jvp_rule
def _buffer_callback_transpose_rule(*args, **kwargs):
del args, kwargs
raise ValueError(
"Buffer callbacks do not support transpose. "
"Please use `jax.custom_vjp` to use callbacks while taking gradients.")
ad.primitive_transposes[buffer_callback_p] = _buffer_callback_transpose_rule
batching.primitive_batchers[buffer_callback_p] = functools.partial(
ffi.ffi_batching_rule, buffer_callback_p
)
def _buffer_callback_lowering(
ctx: mlir.LoweringRuleContext,
*args: Any,
callback,
in_tree: Any,
out_tree: Any,
has_side_effect: bool,
input_output_aliases: Sequence[tuple[int, int]],
command_buffer_compatible: bool,
**_,
):
if len(ctx.module_context.platforms) > 1:
raise NotImplementedError("multi-platform lowering for buffer_callback")
platform = ctx.module_context.platforms[0]
target_name = {
"cpu": "xla_buffer_python_cpu_callback",
"cuda": "xla_buffer_python_gpu_callback",
"rocm": "xla_buffer_python_gpu_callback",
}.get(platform)
if target_name is None:
raise ValueError(f"`buffer_callback` not supported on {platform} backend.")
if command_buffer_compatible and platform in ("cuda", "rocm"):
target_name += "_cmd_buffer"
def wrapped_callback(exec_ctx, *args: Any):
args_in, args_out = util.split_list(args, [in_tree.num_leaves])
py_args_in, py_kwargs_in = tree_util.tree_unflatten(in_tree, args_in)
py_args_out = tree_util.tree_unflatten(out_tree, args_out)
if callback(exec_ctx, py_args_out, *py_args_in, **py_kwargs_in) is not None:
raise ValueError("buffer_callback callback must not return any values.")
return ()
ctx.module_context.add_host_callback(wrapped_callback)
index = np.uint64(len(ctx.module_context.host_callbacks) - 1)
rule = ffi.ffi_lowering(
target_name,
has_side_effect=has_side_effect,
operand_output_aliases=dict(input_output_aliases),
)
return rule(ctx, *args, index=index)
mlir.register_lowering(buffer_callback_p, _buffer_callback_lowering)
|
BufferCallbackEffect
|
python
|
getsentry__sentry
|
src/sentry/release_health/base.py
|
{
"start": 3677,
"end": 4360
}
|
class ____(TypedDict):
#: Adoption rate (based on usercount) for a project's release from 0..100
adoption: float | None
#: Adoption rate (based on sessioncount) for a project's release from 0..100
sessions_adoption: float | None
#: User count for a project's release (past 24h)
users_24h: int | None
#: Sessions count for a project's release (past 24h)
sessions_24h: int | None
#: Sessions count for the entire project (past 24h)
project_users_24h: int | None
#: Sessions count for the entire project (past 24h)
project_sessions_24h: int | None
ReleasesAdoption = Mapping[tuple[ProjectId, ReleaseName], ReleaseAdoption]
|
ReleaseAdoption
|
python
|
readthedocs__readthedocs.org
|
readthedocs/organizations/migrations/0014_update_dj_simple_history.py
|
{
"start": 149,
"end": 1412
}
|
class ____(migrations.Migration):
safe = Safe.before_deploy()
dependencies = [
("organizations", "0013_update_naming"),
]
operations = [
migrations.AlterModelOptions(
name="historicalorganization",
options={
"get_latest_by": ("history_date", "history_id"),
"ordering": ("-history_date", "-history_id"),
"verbose_name": "historical organization",
"verbose_name_plural": "historical organizations",
},
),
migrations.AlterModelOptions(
name="historicalteam",
options={
"get_latest_by": ("history_date", "history_id"),
"ordering": ("-history_date", "-history_id"),
"verbose_name": "historical team",
"verbose_name_plural": "historical teams",
},
),
migrations.AlterField(
model_name="historicalorganization",
name="history_date",
field=models.DateTimeField(db_index=True),
),
migrations.AlterField(
model_name="historicalteam",
name="history_date",
field=models.DateTimeField(db_index=True),
),
]
|
Migration
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py
|
{
"start": 1580,
"end": 1706
}
|
class ____:
a: str = 0
b = field()
c: int = foo()
d = list()
@attr.s(auto_attribs=True) # auto_attribs = True
|
C
|
python
|
kamyu104__LeetCode-Solutions
|
Python/minimum-path-cost-in-a-grid.py
|
{
"start": 40,
"end": 566
}
|
class ____(object):
def minPathCost(self, grid, moveCost):
"""
:type grid: List[List[int]]
:type moveCost: List[List[int]]
:rtype: int
"""
dp = [[0]*len(grid[0]) for _ in xrange(2)]
dp[0] = [grid[0][j] for j in xrange(len(grid[0]))]
for i in xrange(len(grid)-1):
for j in xrange(len(grid[0])):
dp[(i+1)%2][j] = min(dp[i%2][k]+moveCost[x][j] for k, x in enumerate(grid[i]))+grid[i+1][j]
return min(dp[(len(grid)-1)%2])
|
Solution
|
python
|
ray-project__ray
|
python/ray/serve/tests/unit/test_deployment_state.py
|
{
"start": 2515,
"end": 13251
}
|
class ____:
def __init__(
self,
replica_id: ReplicaID,
version: DeploymentVersion,
):
self._replica_id = replica_id
self._actor_name = replica_id.to_full_id_str()
# Will be set when `start()` is called.
self.started = False
# Will be set when `recover()` is called.
self.recovering = False
# Will be set when `start()` is called.
self.version = version
# Initial state for a replica is PENDING_ALLOCATION.
self.status = ReplicaStartupStatus.PENDING_ALLOCATION
# Will be set when `graceful_stop()` is called.
self.stopped = False
# Expected to be set in the test.
self.done_stopping = False
# Will be set when `force_stop()` is called.
self.force_stopped_counter = 0
# Will be set when `check_health()` is called.
self.health_check_called = False
# Returned by the health check.
self.healthy = True
self._is_cross_language = False
self._actor_handle = MockActorHandle()
self._node_id = None
self._node_ip = None
self._node_instance_id = None
self._node_id_is_set = False
self._actor_id = None
self._internal_grpc_port = None
self._pg_bundles = None
self._initialization_latency_s = -1
self._docs_path = None
self._rank = replica_rank_context.get(replica_id.unique_id, None)
self._assign_rank_callback = None
@property
def is_cross_language(self) -> bool:
return self._is_cross_language
@property
def replica_id(self) -> ReplicaID:
return self._replica_id
@property
def deployment_name(self) -> str:
return self._replica_id.deployment_id.name
@property
def actor_handle(self) -> MockActorHandle:
return self._actor_handle
@property
def max_ongoing_requests(self) -> int:
return self.version.deployment_config.max_ongoing_requests
@property
def graceful_shutdown_timeout_s(self) -> float:
return self.version.deployment_config.graceful_shutdown_timeout_s
@property
def health_check_period_s(self) -> float:
return self.version.deployment_config.health_check_period_s
@property
def health_check_timeout_s(self) -> float:
return self.version.deployment_config.health_check_timeout_s
@property
def pid(self) -> Optional[int]:
return None
@property
def actor_id(self) -> Optional[str]:
return self._actor_id
@property
def worker_id(self) -> Optional[str]:
return None
@property
def node_id(self) -> Optional[str]:
if self._node_id_is_set:
return self._node_id
if self.status == ReplicaStartupStatus.SUCCEEDED or self.started:
return "node-id"
return None
@property
def availability_zone(self) -> Optional[str]:
return None
@property
def node_ip(self) -> Optional[str]:
return None
@property
def node_instance_id(self) -> Optional[str]:
return None
@property
def log_file_path(self) -> Optional[str]:
return None
@property
def grpc_port(self) -> Optional[int]:
return None
@property
def placement_group_bundles(self) -> Optional[List[Dict[str, float]]]:
return None
@property
def initialization_latency_s(self) -> float:
return self._initialization_latency_s
def set_docs_path(self, docs_path: str):
self._docs_path = docs_path
@property
def docs_path(self) -> Optional[str]:
return self._docs_path
def set_status(self, status: ReplicaStartupStatus):
self.status = status
def set_ready(self, version: DeploymentVersion = None):
self.status = ReplicaStartupStatus.SUCCEEDED
if version:
self.version_to_be_fetched_from_actor = version
else:
self.version_to_be_fetched_from_actor = self.version
def set_failed_to_start(self):
self.status = ReplicaStartupStatus.FAILED
def set_done_stopping(self):
self.done_stopping = True
def set_unhealthy(self):
self.healthy = False
def set_starting_version(self, version: DeploymentVersion):
"""Mocked deployment_worker return version from reconfigure()"""
self.starting_version = version
def set_node_id(self, node_id: str):
self._node_id = node_id
self._node_id_is_set = True
def set_actor_id(self, actor_id: str):
self._actor_id = actor_id
def start(
self,
deployment_info: DeploymentInfo,
assign_rank_callback: Callable[[ReplicaID], ReplicaRank],
):
self.started = True
self._assign_rank_callback = assign_rank_callback
self._rank = assign_rank_callback(self._replica_id.unique_id)
replica_rank_context[self._replica_id.unique_id] = self._rank
def _on_scheduled_stub(*args, **kwargs):
pass
return ReplicaSchedulingRequest(
replica_id=self._replica_id,
actor_def=Mock(),
actor_resources={},
actor_options={"name": "placeholder"},
actor_init_args=(),
placement_group_bundles=(
deployment_info.replica_config.placement_group_bundles
),
on_scheduled=_on_scheduled_stub,
)
@property
def rank(self) -> Optional[ReplicaRank]:
return self._rank
def reconfigure(
self,
version: DeploymentVersion,
rank: ReplicaRank = None,
):
self.started = True
updating = self.version.requires_actor_reconfigure(version)
self.version = version
self._rank = rank
replica_rank_context[self._replica_id.unique_id] = rank
return updating
def recover(self):
if self.replica_id in dead_replicas_context:
return False
self.recovering = True
self.started = False
self._rank = replica_rank_context.get(self._replica_id.unique_id, None)
return True
def check_ready(self) -> ReplicaStartupStatus:
ready = self.status
self.status = ReplicaStartupStatus.PENDING_INITIALIZATION
if ready == ReplicaStartupStatus.SUCCEEDED and self.recovering:
self.recovering = False
self.started = True
self.version = self.version_to_be_fetched_from_actor
return ready, None
def resource_requirements(self) -> Tuple[str, str]:
assert self.started
return str({"REQUIRED_RESOURCE": 1.0}), str({"AVAILABLE_RESOURCE": 1.0})
@property
def actor_resources(self) -> Dict[str, float]:
return {"CPU": 0.1}
@property
def available_resources(self) -> Dict[str, float]:
# Only used to print a warning.
return {}
def graceful_stop(self) -> None:
assert self.started
self.stopped = True
return self.graceful_shutdown_timeout_s
def check_stopped(self) -> bool:
return self.done_stopping
def force_stop(self, log_shutdown_message: bool = False):
self.force_stopped_counter += 1
def check_health(self):
self.health_check_called = True
return self.healthy
def get_routing_stats(self) -> Dict[str, Any]:
return {}
def get_outbound_deployments(self) -> Optional[List[DeploymentID]]:
return getattr(self, "_outbound_deployments", None)
@property
def route_patterns(self) -> Optional[List[str]]:
return None
def deployment_info(
version: Optional[str] = None,
num_replicas: Optional[int] = 1,
user_config: Optional[Any] = None,
replica_config: Optional[ReplicaConfig] = None,
**config_opts,
) -> Tuple[DeploymentInfo, DeploymentVersion]:
info = DeploymentInfo(
version=version,
start_time_ms=0,
actor_name="abc",
deployment_config=DeploymentConfig(
num_replicas=num_replicas, user_config=user_config, **config_opts
),
replica_config=replica_config or ReplicaConfig.create(lambda x: x),
deployer_job_id="",
)
if version is not None:
code_version = version
else:
code_version = get_random_string()
version = DeploymentVersion(
code_version, info.deployment_config, info.replica_config.ray_actor_options
)
return info, version
def deployment_version(code_version) -> DeploymentVersion:
return DeploymentVersion(code_version, DeploymentConfig(), {})
@pytest.fixture
def mock_deployment_state_manager(
request,
) -> Tuple[DeploymentStateManager, MockTimer, Mock, Mock]:
"""Fully mocked deployment state manager.
i.e kv store and gcs client is mocked so we don't need to initialize
ray. Also, since this is used for some recovery tests, this yields a
method for creating a new mocked deployment state manager.
"""
timer = MockTimer()
with patch(
"ray.serve._private.deployment_state.ActorReplicaWrapper",
new=MockReplicaActorWrapper,
), patch("time.time", new=timer.time), patch(
"ray.serve._private.long_poll.LongPollHost"
) as mock_long_poll, patch(
"ray.get_runtime_context"
):
kv_store = MockKVStore()
cluster_node_info_cache = MockClusterNodeInfoCache()
cluster_node_info_cache.add_node(NodeID.from_random().hex())
autoscaling_state_manager = AutoscalingStateManager()
def create_deployment_state_manager(
actor_names=None,
placement_group_names=None,
create_placement_group_fn_override=None,
):
if actor_names is None:
actor_names = []
if placement_group_names is None:
placement_group_names = []
return DeploymentStateManager(
kv_store,
mock_long_poll,
actor_names,
placement_group_names,
cluster_node_info_cache,
autoscaling_state_manager,
head_node_id_override="fake-head-node-id",
create_placement_group_fn_override=create_placement_group_fn_override,
)
yield (
create_deployment_state_manager,
timer,
cluster_node_info_cache,
autoscaling_state_manager,
)
dead_replicas_context.clear()
replica_rank_context.clear()
@pytest.fixture
def mock_max_per_replica_retry_count():
with patch("ray.serve._private.deployment_state.MAX_PER_REPLICA_RETRY_COUNT", 2):
yield 2
|
MockReplicaActorWrapper
|
python
|
davidhalter__jedi
|
test/completion/descriptors.py
|
{
"start": 0,
"end": 492
}
|
class ____(object):
"""
A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print('Retrieving', self.name)
return self.val
def __set__(self, obj, val):
print('Updating', self.name)
self.val = val
def just_a_method(self):
pass
|
RevealAccess
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP004.py
|
{
"start": 762,
"end": 801
}
|
class ____(
object, # )
):
...
|
A
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-aws/prefect_aws/s3.py
|
{
"start": 27096,
"end": 87083
}
|
class ____(WritableFileSystem, WritableDeploymentStorage, ObjectStorageBlock):
"""
Block used to store data using AWS S3 or S3-compatible object storage like MinIO.
Attributes:
bucket_name: Name of your bucket.
credentials: A block containing your credentials to AWS or MinIO.
bucket_folder: A default path to a folder within the S3 bucket to use
for reading and writing objects.
"""
_logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/d74b16fe84ce626345adf235a47008fea2869a60-225x225.png" # noqa
_block_type_name = "S3 Bucket"
_documentation_url = "https://docs.prefect.io/integrations/prefect-aws" # noqa
bucket_name: str = Field(default=..., description="Name of your bucket.")
credentials: Union[MinIOCredentials, AwsCredentials] = Field(
default_factory=AwsCredentials,
description="A block containing your credentials to AWS or MinIO.",
)
bucket_folder: str = Field(
default="",
description=(
"A default path to a folder within the S3 bucket to use "
"for reading and writing objects."
),
)
@field_validator("credentials", mode="before")
def validate_credentials(cls, value, field):
if isinstance(value, dict):
# There is an issue with pydantic and nested blocks with union
# types, in this case credentials is affected by it. What happens
# is that the credentials block appears to be correctly initialized
# but when it's attached to the parent block it's an
# _uninitialized_ instance without the field attributes.
# This validator is a workaround to check for the correct type
# or fallback to iterating over the possible credential types
# and trying to initialize them.
block_type_slug = value.pop("block_type_slug", None)
if block_type_slug:
credential_classes = (
lookup_type(CredentialsBlock, dispatch_key=block_type_slug),
)
else:
credential_classes = get_args(
cls.model_fields["credentials"].annotation
)
for credentials_cls in credential_classes:
try:
return credentials_cls(**value) # type: ignore
except ValueError:
pass
valid_classes = ", ".join(c.__name__ for c in credential_classes)
raise ValueError(
f"Invalid credentials data: does not match any credential type. Valid types: {valid_classes}"
)
return value
# Property to maintain compatibility with storage block based deployments
@property
def basepath(self) -> str:
"""
The base path of the S3 bucket.
Returns:
str: The base path of the S3 bucket.
"""
return self.bucket_folder
@basepath.setter
def basepath(self, value: str) -> None:
self.bucket_folder = value
def _resolve_path(self, path: str) -> str:
"""
A helper function used in write_path to join `self.basepath` and `path`.
Args:
path: Name of the key, e.g. "file1". Each object in your
bucket has a unique key (or key name).
"""
# If bucket_folder provided, it means we won't write to the root dir of
# the bucket. So we need to add it on the front of the path.
#
# AWS object key naming guidelines require '/' for bucket folders.
# Get POSIX path to prevent `pathlib` from inferring '\' on Windows OS
path = (
(Path(self.bucket_folder) / path).as_posix() if self.bucket_folder else path
)
return path
def _get_s3_client(self):
"""
Authenticate MinIO credentials or AWS credentials and return an S3 client.
This is a helper function called by read_path() or write_path().
"""
return self.credentials.get_client("s3")
def _get_bucket_resource(self):
"""
Retrieves boto3 resource object for the configured bucket
"""
params_override = self.credentials.aws_client_parameters.get_params_override()
bucket = (
self.credentials.get_boto3_session()
.resource("s3", **params_override)
.Bucket(self.bucket_name)
)
return bucket
async def aget_directory(
self, from_path: Optional[str] = None, local_path: Optional[str] = None
) -> None:
"""
Asynchronously copies a folder from the configured S3 bucket to a local directory.
Defaults to copying the entire contents of the block's basepath to the current
working directory.
Args:
from_path: Path in S3 bucket to download from. Defaults to the block's
configured basepath.
local_path: Local path to download S3 contents to. Defaults to the current
working directory.
"""
bucket_folder = self.bucket_folder
if from_path is None:
from_path = str(bucket_folder) if bucket_folder else ""
if local_path is None:
local_path = str(Path(".").absolute())
else:
local_path = str(Path(local_path).expanduser())
bucket = self._get_bucket_resource()
for obj in bucket.objects.filter(Prefix=from_path):
if obj.key[-1] == "/":
# object is a folder and will be created if it contains any objects
continue
target = os.path.join(
local_path,
os.path.relpath(obj.key, from_path),
)
os.makedirs(os.path.dirname(target), exist_ok=True)
await run_sync_in_worker_thread(bucket.download_file, obj.key, target)
@async_dispatch(aget_directory)
def get_directory(
self, from_path: Optional[str] = None, local_path: Optional[str] = None
) -> None:
"""
Copies a folder from the configured S3 bucket to a local directory.
Defaults to copying the entire contents of the block's basepath to the current
working directory.
Args:
from_path: Path in S3 bucket to download from. Defaults to the block's
configured basepath.
local_path: Local path to download S3 contents to. Defaults to the current
working directory.
"""
bucket_folder = self.bucket_folder
if from_path is None:
from_path = str(bucket_folder) if bucket_folder else ""
if local_path is None:
local_path = str(Path(".").absolute())
else:
local_path = str(Path(local_path).expanduser())
bucket = self._get_bucket_resource()
for obj in bucket.objects.filter(Prefix=from_path):
if obj.key[-1] == "/":
# object is a folder and will be created if it contains any objects
continue
target = os.path.join(
local_path,
os.path.relpath(obj.key, from_path),
)
os.makedirs(os.path.dirname(target), exist_ok=True)
bucket.download_file(obj.key, target)
async def aput_directory(
self,
local_path: Optional[str] = None,
to_path: Optional[str] = None,
ignore_file: Optional[str] = None,
) -> int:
"""
Asynchronously uploads a directory from a given local path to the configured S3 bucket in a
given folder.
Defaults to uploading the entire contents the current working directory to the
block's basepath.
Args:
local_path: Path to local directory to upload from.
to_path: Path in S3 bucket to upload to. Defaults to block's configured
basepath.
ignore_file: Path to file containing gitignore style expressions for
filepaths to ignore.
"""
to_path = "" if to_path is None else to_path
if local_path is None:
local_path = "."
included_files = None
if ignore_file:
with open(ignore_file, "r") as f:
ignore_patterns = f.readlines()
included_files = filter_files(local_path, ignore_patterns)
uploaded_file_count = 0
for local_file_path in Path(local_path).expanduser().rglob("*"):
if (
included_files is not None
and str(local_file_path.relative_to(local_path)) not in included_files
):
continue
elif not local_file_path.is_dir():
remote_file_path = Path(to_path) / local_file_path.relative_to(
local_path
)
with open(local_file_path, "rb") as local_file:
local_file_content = local_file.read()
await self.awrite_path(
remote_file_path.as_posix(), content=local_file_content
)
uploaded_file_count += 1
return uploaded_file_count
@async_dispatch(aput_directory)
def put_directory(
self,
local_path: Optional[str] = None,
to_path: Optional[str] = None,
ignore_file: Optional[str] = None,
) -> int:
"""
Uploads a directory from a given local path to the configured S3 bucket in a
given folder.
Defaults to uploading the entire contents the current working directory to the
block's basepath.
Args:
local_path: Path to local directory to upload from.
to_path: Path in S3 bucket to upload to. Defaults to block's configured
basepath.
ignore_file: Path to file containing gitignore style expressions for
filepaths to ignore.
"""
to_path = "" if to_path is None else to_path
if local_path is None:
local_path = "."
included_files = None
if ignore_file:
with open(ignore_file, "r") as f:
ignore_patterns = f.readlines()
included_files = filter_files(local_path, ignore_patterns)
uploaded_file_count = 0
for local_file_path in Path(local_path).expanduser().rglob("*"):
if (
included_files is not None
and str(local_file_path.relative_to(local_path)) not in included_files
):
continue
elif not local_file_path.is_dir():
remote_file_path = Path(to_path) / local_file_path.relative_to(
local_path
)
with open(local_file_path, "rb") as local_file:
local_file_content = local_file.read()
self.write_path(
remote_file_path.as_posix(), content=local_file_content, _sync=True
)
uploaded_file_count += 1
return uploaded_file_count
def _read_sync(self, key: str) -> bytes:
"""
Called by read_path(). Creates an S3 client and retrieves the
contents from a specified path.
"""
s3_client = self._get_s3_client()
with io.BytesIO() as stream:
s3_client.download_fileobj(Bucket=self.bucket_name, Key=key, Fileobj=stream)
stream.seek(0)
output = stream.read()
return output
async def aread_path(self, path: str) -> bytes:
"""
Asynchronously reads the contents of a specified path from the S3 bucket.
Provide the entire path to the key in S3.
Args:
path: Entire path to (and including) the key.
Example:
Read "subfolder/file1" contents from an S3 bucket named "bucket":
```python
from prefect_aws import AwsCredentials
from prefect_aws.s3 import S3Bucket
aws_creds = AwsCredentials(
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
s3_bucket_block = S3Bucket(
bucket_name="bucket",
credentials=aws_creds,
bucket_folder="subfolder"
)
key_contents = await s3_bucket_block.aread_path(path="subfolder/file1")
```
"""
path = self._resolve_path(path)
return await run_sync_in_worker_thread(self._read_sync, path)
@async_dispatch(aread_path)
def read_path(self, path: str) -> bytes:
"""
Read specified path from S3 and return contents. Provide the entire
path to the key in S3.
Args:
path: Entire path to (and including) the key.
Example:
Read "subfolder/file1" contents from an S3 bucket named "bucket":
```python
from prefect_aws import AwsCredentials
from prefect_aws.s3 import S3Bucket
aws_creds = AwsCredentials(
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)
s3_bucket_block = S3Bucket(
bucket_name="bucket",
credentials=aws_creds,
bucket_folder="subfolder"
)
key_contents = s3_bucket_block.read_path(path="subfolder/file1")
```
"""
path = self._resolve_path(path)
return self._read_sync(path)
def _write_sync(self, key: str, data: bytes) -> None:
"""
Called by write_path(). Creates an S3 client and uploads a file
object.
"""
s3_client = self._get_s3_client()
with io.BytesIO(data) as stream:
s3_client.upload_fileobj(Fileobj=stream, Bucket=self.bucket_name, Key=key)
async def awrite_path(self, path: str, content: bytes) -> str:
"""
Asynchronously writes to an S3 bucket.
Args:
path: The key name. Each object in your bucket has a unique
key (or key name).
content: What you are uploading to S3.
Example:
Write data to the path `dogs/small_dogs/havanese` in an S3 Bucket:
```python
from prefect_aws import MinioCredentials
from prefect_aws.s3 import S3Bucket
minio_creds = MinIOCredentials(
minio_root_user = "minioadmin",
minio_root_password = "minioadmin",
)
s3_bucket_block = S3Bucket(
bucket_name="bucket",
minio_credentials=minio_creds,
bucket_folder="dogs/smalldogs",
endpoint_url="http://localhost:9000",
)
s3_havanese_path = await s3_bucket_block.awrite_path(path="havanese", content=data)
```
"""
path = self._resolve_path(path)
await run_sync_in_worker_thread(self._write_sync, path, content)
return path
@async_dispatch(awrite_path)
def write_path(self, path: str, content: bytes) -> str:
"""
Writes to an S3 bucket.
Args:
path: The key name. Each object in your bucket has a unique
key (or key name).
content: What you are uploading to S3.
Example:
Write data to the path `dogs/small_dogs/havanese` in an S3 Bucket:
```python
from prefect_aws import MinioCredentials
from prefect_aws.s3 import S3Bucket
minio_creds = MinIOCredentials(
minio_root_user = "minioadmin",
minio_root_password = "minioadmin",
)
s3_bucket_block = S3Bucket(
bucket_name="bucket",
minio_credentials=minio_creds,
bucket_folder="dogs/smalldogs",
endpoint_url="http://localhost:9000",
)
s3_havanese_path = s3_bucket_block.write_path(path="havanese", content=data)
```
"""
path = self._resolve_path(path)
self._write_sync(path, content)
return path
# NEW BLOCK INTERFACE METHODS BELOW
@staticmethod
def _list_objects_sync(page_iterator: PageIterator) -> List[Dict[str, Any]]:
"""
Synchronous method to collect S3 objects into a list
Args:
page_iterator: AWS Paginator for S3 objects
Returns:
List[Dict]: List of object information
"""
return [
content for page in page_iterator for content in page.get("Contents", [])
]
def _join_bucket_folder(self, bucket_path: str = "") -> str:
"""
Joins the base bucket folder to the bucket path.
NOTE: If a method reuses another method in this class, be careful to not
call this twice because it'll join the bucket folder twice.
See https://github.com/PrefectHQ/prefect-aws/issues/141 for a past issue.
"""
if not self.bucket_folder and not bucket_path:
# there's a difference between "." and "", at least in the tests
return ""
bucket_path = str(bucket_path)
if self.bucket_folder != "" and bucket_path.startswith(self.bucket_folder):
self.logger.info(
f"Bucket path {bucket_path!r} is already prefixed with "
f"bucket folder {self.bucket_folder!r}; is this intentional?"
)
return (Path(self.bucket_folder) / bucket_path).as_posix() + (
"" if not bucket_path.endswith("/") else "/"
)
def _list_objects_setup(
self,
folder: str = "",
delimiter: str = "",
page_size: Optional[int] = None,
max_items: Optional[int] = None,
jmespath_query: Optional[str] = None,
) -> Tuple[PageIterator, str]:
bucket_path = self._join_bucket_folder(folder)
client = self.credentials.get_s3_client()
paginator = client.get_paginator("list_objects_v2")
page_iterator = paginator.paginate(
Bucket=self.bucket_name,
Prefix=bucket_path,
Delimiter=delimiter,
PaginationConfig={"PageSize": page_size, "MaxItems": max_items},
)
if jmespath_query:
page_iterator = page_iterator.search(f"{jmespath_query} | {{Contents: @}}")
return page_iterator, bucket_path
async def alist_objects(
self,
folder: str = "",
delimiter: str = "",
page_size: Optional[int] = None,
max_items: Optional[int] = None,
jmespath_query: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""
Asynchronously lists objects in the S3 bucket.
Args:
folder: Folder to list objects from.
delimiter: Character used to group keys of listed objects.
page_size: Number of objects to return in each request to the AWS API.
max_items: Maximum number of objects that to be returned by task.
jmespath_query: Query used to filter objects based on object attributes refer to
the [boto3 docs](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath)
for more information on how to construct queries.
Returns:
List of objects and their metadata in the bucket.
Examples:
List objects under the `base_folder`.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.alist_objects("base_folder")
```
""" # noqa: E501
page_iterator, bucket_path = self._list_objects_setup(
folder, delimiter, page_size, max_items, jmespath_query
)
self.logger.info(f"Listing objects in bucket {bucket_path}.")
objects = await run_sync_in_worker_thread(
self._list_objects_sync, page_iterator
)
return objects
@async_dispatch(alist_objects)
def list_objects(
self,
folder: str = "",
delimiter: str = "",
page_size: Optional[int] = None,
max_items: Optional[int] = None,
jmespath_query: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""
Args:
folder: Folder to list objects from.
delimiter: Character used to group keys of listed objects.
page_size: Number of objects to return in each request to the AWS API.
max_items: Maximum number of objects that to be returned by task.
jmespath_query: Query used to filter objects based on object attributes refer to
the [boto3 docs](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath)
for more information on how to construct queries.
Returns:
List of objects and their metadata in the bucket.
Examples:
List objects under the `base_folder`.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.list_objects("base_folder")
```
""" # noqa: E501
page_iterator, bucket_path = self._list_objects_setup(
folder, delimiter, page_size, max_items, jmespath_query
)
self.logger.info(f"Listing objects in bucket {bucket_path}.")
return self._list_objects_sync(page_iterator)
async def adownload_object_to_path(
self,
from_path: str,
to_path: Optional[Union[str, Path]],
**download_kwargs: Dict[str, Any],
) -> Path:
"""
Asynchronously downloads an object from the S3 bucket to a path.
Args:
from_path: The path to the object to download; this gets prefixed
with the bucket_folder.
to_path: The path to download the object to. If not provided, the
object's name will be used.
**download_kwargs: Additional keyword arguments to pass to
`Client.download_file`.
Returns:
The absolute path that the object was downloaded to.
Examples:
Download my_folder/notes.txt object to notes.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.adownload_object_to_path("my_folder/notes.txt", "notes.txt")
```
"""
if to_path is None:
to_path = Path(from_path).name
# making path absolute, but converting back to str here
# since !r looks nicer that way and filename arg expects str
to_path = str(Path(to_path).absolute())
bucket_path = self._join_bucket_folder(from_path)
client = self.credentials.get_s3_client()
self.logger.debug(
f"Preparing to download object from bucket {self.bucket_name!r} "
f"path {bucket_path!r} to {to_path!r}."
)
await run_sync_in_worker_thread(
client.download_file,
Bucket=self.bucket_name,
Key=bucket_path,
Filename=to_path,
**download_kwargs,
)
self.logger.info(
f"Downloaded object from bucket {self.bucket_name!r} path {bucket_path!r} "
f"to {to_path!r}."
)
return Path(to_path)
@async_dispatch(adownload_object_to_path)
def download_object_to_path(
self,
from_path: str,
to_path: Optional[Union[str, Path]],
**download_kwargs: Dict[str, Any],
) -> Path:
"""
Downloads an object from the S3 bucket to a path.
Args:
from_path: The path to the object to download; this gets prefixed
with the bucket_folder.
to_path: The path to download the object to. If not provided, the
object's name will be used.
**download_kwargs: Additional keyword arguments to pass to
`Client.download_file`.
Returns:
The absolute path that the object was downloaded to.
Examples:
Download my_folder/notes.txt object to notes.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.download_object_to_path("my_folder/notes.txt", "notes.txt")
```
"""
if to_path is None:
to_path = Path(from_path).name
# making path absolute, but converting back to str here
# since !r looks nicer that way and filename arg expects str
to_path = str(Path(to_path).absolute())
bucket_path = self._join_bucket_folder(from_path)
client = self.credentials.get_s3_client()
self.logger.debug(
f"Preparing to download object from bucket {self.bucket_name!r} "
f"path {bucket_path!r} to {to_path!r}."
)
client.download_file(
Bucket=self.bucket_name,
Key=bucket_path,
Filename=to_path,
**download_kwargs,
)
self.logger.info(
f"Downloaded object from bucket {self.bucket_name!r} path {bucket_path!r} "
f"to {to_path!r}."
)
return Path(to_path)
async def adownload_object_to_file_object(
self,
from_path: str,
to_file_object: BinaryIO,
**download_kwargs: Dict[str, Any],
) -> BinaryIO:
"""
Asynchronously downloads an object from the object storage service to a file-like object,
which can be a BytesIO object or a BufferedWriter.
Args:
from_path: The path to the object to download from; this gets prefixed
with the bucket_folder.
to_file_object: The file-like object to download the object to.
**download_kwargs: Additional keyword arguments to pass to
`Client.download_fileobj`.
Returns:
The file-like object that the object was downloaded to.
Examples:
Download my_folder/notes.txt object to a BytesIO object.
```python
from io import BytesIO
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with BytesIO() as buf:
await s3_bucket.adownload_object_to_file_object("my_folder/notes.txt", buf)
```
Download my_folder/notes.txt object to a BufferedWriter.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with open("notes.txt", "wb") as f:
await s3_bucket.adownload_object_to_file_object("my_folder/notes.txt", f)
```
"""
client = self.credentials.get_s3_client()
bucket_path = self._join_bucket_folder(from_path)
self.logger.debug(
f"Preparing to download object from bucket {self.bucket_name!r} "
f"path {bucket_path!r} to file object."
)
await run_sync_in_worker_thread(
client.download_fileobj,
Bucket=self.bucket_name,
Key=bucket_path,
Fileobj=to_file_object,
**download_kwargs,
)
self.logger.info(
f"Downloaded object from bucket {self.bucket_name!r} path {bucket_path!r} "
"to file object."
)
return to_file_object
@async_dispatch(adownload_object_to_file_object)
def download_object_to_file_object(
self,
from_path: str,
to_file_object: BinaryIO,
**download_kwargs: Dict[str, Any],
) -> BinaryIO:
"""
Downloads an object from the object storage service to a file-like object,
which can be a BytesIO object or a BufferedWriter.
Args:
from_path: The path to the object to download from; this gets prefixed
with the bucket_folder.
to_file_object: The file-like object to download the object to.
**download_kwargs: Additional keyword arguments to pass to
`Client.download_fileobj`.
Returns:
The file-like object that the object was downloaded to.
Examples:
Download my_folder/notes.txt object to a BytesIO object.
```python
from io import BytesIO
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with BytesIO() as buf:
s3_bucket.download_object_to_file_object("my_folder/notes.txt", buf)
```
Download my_folder/notes.txt object to a BufferedWriter.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with open("notes.txt", "wb") as f:
s3_bucket.download_object_to_file_object("my_folder/notes.txt", f)
```
"""
client = self.credentials.get_s3_client()
bucket_path = self._join_bucket_folder(from_path)
self.logger.debug(
f"Preparing to download object from bucket {self.bucket_name!r} "
f"path {bucket_path!r} to file object."
)
client.download_fileobj(
Bucket=self.bucket_name,
Key=bucket_path,
Fileobj=to_file_object,
**download_kwargs,
)
self.logger.info(
f"Downloaded object from bucket {self.bucket_name!r} path {bucket_path!r} "
"to file object."
)
return to_file_object
async def adownload_folder_to_path(
self,
from_folder: str,
to_folder: Optional[Union[str, Path]] = None,
**download_kwargs: Dict[str, Any],
) -> Path:
"""
Asynchronously downloads objects *within* a folder (excluding the folder itself)
from the S3 bucket to a folder.
Args:
from_folder: The path to the folder to download from.
to_folder: The path to download the folder to.
**download_kwargs: Additional keyword arguments to pass to
`Client.download_file`.
Returns:
The absolute path that the folder was downloaded to.
Examples:
Download my_folder to a local folder named my_folder.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.adownload_folder_to_path("my_folder", "my_folder")
```
"""
if to_folder is None:
to_folder = ""
to_folder = Path(to_folder).absolute()
client = self.credentials.get_s3_client()
objects = await self.list_objects(folder=from_folder)
# do not call self._join_bucket_folder for filter
# because it's built-in to that method already!
# however, we still need to do it because we're using relative_to
bucket_folder = self._join_bucket_folder(from_folder)
async_coros = []
for object in objects:
bucket_path = Path(object["Key"]).relative_to(bucket_folder)
# this skips the actual directory itself, e.g.
# `my_folder/` will be skipped
# `my_folder/notes.txt` will be downloaded
if bucket_path.is_dir():
continue
to_path = to_folder / bucket_path
to_path.parent.mkdir(parents=True, exist_ok=True)
to_path = str(to_path) # must be string
self.logger.info(
f"Downloading object from bucket {self.bucket_name!r} path "
f"{bucket_path.as_posix()!r} to {to_path!r}."
)
async_coros.append(
run_sync_in_worker_thread(
client.download_file,
Bucket=self.bucket_name,
Key=object["Key"],
Filename=to_path,
**download_kwargs,
)
)
await asyncio.gather(*async_coros)
return Path(to_folder)
@async_dispatch(adownload_folder_to_path)
def download_folder_to_path(
self,
from_folder: str,
to_folder: Optional[Union[str, Path]] = None,
**download_kwargs: Dict[str, Any],
) -> Path:
"""
Downloads objects *within* a folder (excluding the folder itself)
from the S3 bucket to a folder.
Changed in version 0.6.0.
Args:
from_folder: The path to the folder to download from.
to_folder: The path to download the folder to.
**download_kwargs: Additional keyword arguments to pass to
`Client.download_file`.
Returns:
The absolute path that the folder was downloaded to.
Examples:
Download my_folder to a local folder named my_folder.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.download_folder_to_path("my_folder", "my_folder")
```
"""
if to_folder is None:
to_folder = ""
to_folder = Path(to_folder).absolute()
client = self.credentials.get_s3_client()
objects = self.list_objects(folder=from_folder)
# do not call self._join_bucket_folder for filter
# because it's built-in to that method already!
# however, we still need to do it because we're using relative_to
bucket_folder = self._join_bucket_folder(from_folder)
assert isinstance(objects, list), "list of objects expected"
for object in objects:
bucket_path = Path(object["Key"]).relative_to(bucket_folder)
# this skips the actual directory itself, e.g.
# `my_folder/` will be skipped
# `my_folder/notes.txt` will be downloaded
if bucket_path.is_dir():
continue
to_path = to_folder / bucket_path
to_path.parent.mkdir(parents=True, exist_ok=True)
to_path = str(to_path) # must be string
self.logger.info(
f"Downloading object from bucket {self.bucket_name!r} path "
f"{bucket_path.as_posix()!r} to {to_path!r}."
)
client.download_file(
Bucket=self.bucket_name,
Key=object["Key"],
Filename=to_path,
**download_kwargs,
)
return Path(to_folder)
async def astream_from(
self,
bucket: "S3Bucket",
from_path: str,
to_path: Optional[str] = None,
**upload_kwargs: Dict[str, Any],
) -> str:
"""Asynchronously streams an object from another bucket to this bucket. Requires the
object to be downloaded and uploaded in chunks. If `self`'s credentials
allow for writes to the other bucket, try using `S3Bucket.copy_object`.
Added in version 0.5.3.
Args:
bucket: The bucket to stream from.
from_path: The path of the object to stream.
to_path: The path to stream the object to. Defaults to the object's name.
**upload_kwargs: Additional keyword arguments to pass to
`Client.upload_fileobj`.
Returns:
The path that the object was uploaded to.
Examples:
Stream notes.txt from your-bucket/notes.txt to my-bucket/landed/notes.txt.
```python
from prefect_aws.s3 import S3Bucket
your_s3_bucket = S3Bucket.load("your-bucket")
my_s3_bucket = S3Bucket.load("my-bucket")
await my_s3_bucket.astream_from(
your_s3_bucket,
"notes.txt",
to_path="landed/notes.txt"
)
```
"""
if to_path is None:
to_path = Path(from_path).name
# Get the source object's StreamingBody
_from_path: str = bucket._join_bucket_folder(from_path)
from_client = bucket.credentials.get_s3_client()
obj = await run_sync_in_worker_thread(
from_client.get_object, Bucket=bucket.bucket_name, Key=_from_path
)
body: StreamingBody = obj["Body"]
# Upload the StreamingBody to this bucket
bucket_path = str(self._join_bucket_folder(to_path))
to_client = self.credentials.get_s3_client()
await run_sync_in_worker_thread(
to_client.upload_fileobj,
Fileobj=body,
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
self.logger.info(
f"Streamed s3://{bucket.bucket_name}/{_from_path} to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
return bucket_path
@async_dispatch(astream_from)
def stream_from(
self,
bucket: "S3Bucket",
from_path: str,
to_path: Optional[str] = None,
**upload_kwargs: Dict[str, Any],
) -> str:
"""Streams an object from another bucket to this bucket. Requires the
object to be downloaded and uploaded in chunks. If `self`'s credentials
allow for writes to the other bucket, try using `S3Bucket.copy_object`.
Args:
bucket: The bucket to stream from.
from_path: The path of the object to stream.
to_path: The path to stream the object to. Defaults to the object's name.
**upload_kwargs: Additional keyword arguments to pass to
`Client.upload_fileobj`.
Returns:
The path that the object was uploaded to.
Examples:
Stream notes.txt from your-bucket/notes.txt to my-bucket/landed/notes.txt.
```python
from prefect_aws.s3 import S3Bucket
your_s3_bucket = S3Bucket.load("your-bucket")
my_s3_bucket = S3Bucket.load("my-bucket")
my_s3_bucket.stream_from(
your_s3_bucket,
"notes.txt",
to_path="landed/notes.txt"
)
```
"""
if to_path is None:
to_path = Path(from_path).name
# Get the source object's StreamingBody
_from_path: str = bucket._join_bucket_folder(from_path)
from_client = bucket.credentials.get_s3_client()
obj = from_client.get_object(Bucket=bucket.bucket_name, Key=_from_path)
body: StreamingBody = obj["Body"]
# Upload the StreamingBody to this bucket
bucket_path = str(self._join_bucket_folder(to_path))
to_client = self.credentials.get_s3_client()
to_client.upload_fileobj(
Fileobj=body,
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
self.logger.info(
f"Streamed s3://{bucket.bucket_name}/{_from_path} to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
return bucket_path
async def aupload_from_path(
self,
from_path: Union[str, Path],
to_path: Optional[str] = None,
**upload_kwargs: Dict[str, Any],
) -> str:
"""
Asynchronously uploads an object from a path to the S3 bucket.
Added in version 0.5.3.
Args:
from_path: The path to the file to upload from.
to_path: The path to upload the file to.
**upload_kwargs: Additional keyword arguments to pass to `Client.upload`.
Returns:
The path that the object was uploaded to.
Examples:
Upload notes.txt to my_folder/notes.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.aupload_from_path("notes.txt", "my_folder/notes.txt")
```
"""
from_path = str(Path(from_path).absolute())
if to_path is None:
to_path = Path(from_path).name
bucket_path = str(self._join_bucket_folder(to_path))
client = self.credentials.get_s3_client()
await run_sync_in_worker_thread(
client.upload_file,
Filename=from_path,
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
self.logger.info(
f"Uploaded from {from_path!r} to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
return bucket_path
@async_dispatch(aupload_from_path)
def upload_from_path(
self,
from_path: Union[str, Path],
to_path: Optional[str] = None,
**upload_kwargs: Dict[str, Any],
) -> str:
"""
Uploads an object from a path to the S3 bucket.
Args:
from_path: The path to the file to upload from.
to_path: The path to upload the file to.
**upload_kwargs: Additional keyword arguments to pass to `Client.upload`.
Returns:
The path that the object was uploaded to.
Examples:
Upload notes.txt to my_folder/notes.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.upload_from_path("notes.txt", "my_folder/notes.txt")
```
"""
from_path = str(Path(from_path).absolute())
if to_path is None:
to_path = Path(from_path).name
bucket_path = str(self._join_bucket_folder(to_path))
client = self.credentials.get_s3_client()
client.upload_file(
Filename=from_path,
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
self.logger.info(
f"Uploaded from {from_path!r} to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
return bucket_path
async def aupload_from_file_object(
self, from_file_object: BinaryIO, to_path: str, **upload_kwargs: Dict[str, Any]
) -> str:
"""
Asynchronously uploads an object to the S3 bucket from a file-like object,
which can be a BytesIO object or a BufferedReader.
Args:
from_file_object: The file-like object to upload from.
to_path: The path to upload the object to.
**upload_kwargs: Additional keyword arguments to pass to
`Client.upload_fileobj`.
Returns:
The path that the object was uploaded to.
Examples:
Upload BytesIO object to my_folder/notes.txt.
```python
from io import BytesIO
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with open("notes.txt", "rb") as f:
await s3_bucket.aupload_from_file_object(f, "my_folder/notes.txt")
```
Upload BufferedReader object to my_folder/notes.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with open("notes.txt", "rb") as f:
s3_bucket.upload_from_file_object(
f, "my_folder/notes.txt"
)
```
"""
bucket_path = str(self._join_bucket_folder(to_path))
client = self.credentials.get_s3_client()
await run_sync_in_worker_thread(
client.upload_fileobj,
Fileobj=from_file_object,
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
self.logger.info(
"Uploaded from file object to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
return bucket_path
@async_dispatch(aupload_from_file_object)
def upload_from_file_object(
self, from_file_object: BinaryIO, to_path: str, **upload_kwargs: Dict[str, Any]
) -> str:
"""
Uploads an object to the S3 bucket from a file-like object,
which can be a BytesIO object or a BufferedReader.
Args:
from_file_object: The file-like object to upload from.
to_path: The path to upload the object to.
**upload_kwargs: Additional keyword arguments to pass to
`Client.upload_fileobj`.
Returns:
The path that the object was uploaded to.
Examples:
Upload BytesIO object to my_folder/notes.txt.
```python
from io import BytesIO
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with open("notes.txt", "rb") as f:
s3_bucket.upload_from_file_object(f, "my_folder/notes.txt")
```
Upload BufferedReader object to my_folder/notes.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
with open("notes.txt", "rb") as f:
s3_bucket.upload_from_file_object(
f, "my_folder/notes.txt"
)
```
"""
bucket_path = str(self._join_bucket_folder(to_path))
client = self.credentials.get_s3_client()
client.upload_fileobj(
Fileobj=from_file_object,
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
self.logger.info(
"Uploaded from file object to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
return bucket_path
async def aupload_from_folder(
self,
from_folder: Union[str, Path],
to_folder: Optional[str] = None,
**upload_kwargs: Dict[str, Any],
) -> Union[str, None]:
"""
Asynchronously uploads files *within* a folder (excluding the folder itself)
to the object storage service folder. Added in version prefect-aws==0.5.3.
Args:
from_folder: The path to the folder to upload from.
to_folder: The path to upload the folder to.
**upload_kwargs: Additional keyword arguments to pass to
`Client.upload_fileobj`.
Returns:
The path that the folder was uploaded to.
Examples:
Upload contents from my_folder to new_folder.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.aupload_from_folder("my_folder", "new_folder")
```
"""
from_folder = Path(from_folder)
bucket_folder = self._join_bucket_folder(to_folder or "")
num_uploaded = 0
client = self.credentials.get_s3_client()
async_coros = []
for from_path in from_folder.rglob("**/*"):
# this skips the actual directory itself, e.g.
# `my_folder/` will be skipped
# `my_folder/notes.txt` will be uploaded
if from_path.is_dir():
continue
bucket_path = (
Path(bucket_folder) / from_path.relative_to(from_folder)
).as_posix()
self.logger.info(
f"Uploading from {str(from_path)!r} to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
async_coros.append(
run_sync_in_worker_thread(
client.upload_file,
Filename=str(from_path),
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
)
num_uploaded += 1
await asyncio.gather(*async_coros)
if num_uploaded == 0:
self.logger.warning(f"No files were uploaded from {str(from_folder)!r}.")
else:
self.logger.info(
f"Uploaded {num_uploaded} files from {str(from_folder)!r} to "
f"the bucket {self.bucket_name!r} path {bucket_path!r}"
)
return to_folder
@async_dispatch(aupload_from_folder)
def upload_from_folder(
self,
from_folder: Union[str, Path],
to_folder: Optional[str] = None,
**upload_kwargs: Dict[str, Any],
) -> Union[str, None]:
"""
Uploads files *within* a folder (excluding the folder itself)
to the object storage service folder.
Args:
from_folder: The path to the folder to upload from.
to_folder: The path to upload the folder to.
**upload_kwargs: Additional keyword arguments to pass to
`Client.upload_fileobj`.
Returns:
The path that the folder was uploaded to.
Examples:
Upload contents from my_folder to new_folder.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.upload_from_folder("my_folder", "new_folder")
```
"""
from_folder = Path(from_folder)
bucket_folder = self._join_bucket_folder(to_folder or "")
num_uploaded = 0
client = self.credentials.get_s3_client()
for from_path in from_folder.rglob("**/*"):
# this skips the actual directory itself, e.g.
# `my_folder/` will be skipped
# `my_folder/notes.txt` will be uploaded
if from_path.is_dir():
continue
bucket_path = (
Path(bucket_folder) / from_path.relative_to(from_folder)
).as_posix()
self.logger.info(
f"Uploading from {str(from_path)!r} to the bucket "
f"{self.bucket_name!r} path {bucket_path!r}."
)
client.upload_file(
Filename=str(from_path),
Bucket=self.bucket_name,
Key=bucket_path,
**upload_kwargs,
)
num_uploaded += 1
if num_uploaded == 0:
self.logger.warning(f"No files were uploaded from {str(from_folder)!r}.")
else:
self.logger.info(
f"Uploaded {num_uploaded} files from {str(from_folder)!r} to "
f"the bucket {self.bucket_name!r} path {bucket_path!r}"
)
return to_folder
def copy_object(
self,
from_path: Union[str, Path],
to_path: Union[str, Path],
to_bucket: Optional[Union["S3Bucket", str]] = None,
**copy_kwargs,
) -> str:
"""Uses S3's internal
[CopyObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html)
to copy objects within or between buckets. To copy objects between buckets,
`self`'s credentials must have permission to read the source object and write
to the target object. If the credentials do not have those permissions, try
using `S3Bucket.stream_from`.
Args:
from_path: The path of the object to copy.
to_path: The path to copy the object to.
to_bucket: The bucket to copy to. Defaults to the current bucket.
**copy_kwargs: Additional keyword arguments to pass to
`S3Client.copy_object`.
Returns:
The path that the object was copied to. Excludes the bucket name.
Examples:
Copy notes.txt from my_folder/notes.txt to my_folder/notes_copy.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.copy_object("my_folder/notes.txt", "my_folder/notes_copy.txt")
```
Copy notes.txt from my_folder/notes.txt to my_folder/notes_copy.txt in
another bucket.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.copy_object(
"my_folder/notes.txt",
"my_folder/notes_copy.txt",
to_bucket="other-bucket"
)
```
"""
s3_client = self.credentials.get_s3_client()
source_bucket_name = self.bucket_name
source_path = self._resolve_path(Path(from_path).as_posix())
# Default to copying within the same bucket
to_bucket = to_bucket or self
target_bucket_name: str
target_path: str
if isinstance(to_bucket, S3Bucket):
target_bucket_name = to_bucket.bucket_name
target_path = to_bucket._resolve_path(Path(to_path).as_posix())
elif isinstance(to_bucket, str):
target_bucket_name = to_bucket
target_path = Path(to_path).as_posix()
else:
raise TypeError(
f"to_bucket must be a string or S3Bucket, not {type(to_bucket)}"
)
self.logger.info(
"Copying object from bucket %s with key %s to bucket %s with key %s",
source_bucket_name,
source_path,
target_bucket_name,
target_path,
)
s3_client.copy_object(
CopySource={"Bucket": source_bucket_name, "Key": source_path},
Bucket=target_bucket_name,
Key=target_path,
**copy_kwargs,
)
return target_path
def _move_object_setup(
self,
from_path: Union[str, Path],
to_path: Union[str, Path],
to_bucket: Optional[Union["S3Bucket", str]] = None,
) -> Tuple[str, str, str, str]:
source_bucket_name = self.bucket_name
source_path = self._resolve_path(Path(from_path).as_posix())
# Default to moving within the same bucket
to_bucket = to_bucket or self
target_bucket_name: str
target_path: str
if isinstance(to_bucket, S3Bucket):
target_bucket_name = to_bucket.bucket_name
target_path = to_bucket._resolve_path(Path(to_path).as_posix())
elif isinstance(to_bucket, str):
target_bucket_name = to_bucket
target_path = Path(to_path).as_posix()
else:
raise TypeError(
f"to_bucket must be a string or S3Bucket, not {type(to_bucket)}"
)
self.logger.info(
"Moving object from s3://%s/%s to s3://%s/%s",
source_bucket_name,
source_path,
target_bucket_name,
target_path,
)
return source_bucket_name, source_path, target_bucket_name, target_path
async def amove_object(
self,
from_path: Union[str, Path],
to_path: Union[str, Path],
to_bucket: Optional[Union["S3Bucket", str]] = None,
) -> str:
"""Asynchronously uses S3's internal CopyObject and DeleteObject to move objects
within or between buckets. To move objects between buckets, `self`'s credentials
must have permission to read and delete the source object and write to the target
object. If the credentials do not have those permissions, this method will raise
an error. If the credentials have permission to read the source object but not
delete it, the object will be copied but not deleted.
Args:
from_path: The path of the object to move.
to_path: The path to move the object to.
to_bucket: The bucket to move to. Defaults to the current bucket.
Returns:
The path that the object was moved to. Excludes the bucket name.
Examples:
Move notes.txt from my_folder/notes.txt to my_folder/notes_copy.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.amove_object("my_folder/notes.txt", "my_folder/notes_copy.txt")
```
Move notes.txt from my_folder/notes.txt to my_folder/notes_copy.txt in
another bucket.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
await s3_bucket.amove_object(
"my_folder/notes.txt",
"my_folder/notes_copy.txt",
to_bucket="other-bucket"
)
```
"""
s3_client = self.credentials.get_s3_client()
(
source_bucket_name,
source_path,
target_bucket_name,
target_path,
) = self._move_object_setup(from_path, to_path, to_bucket)
# If invalid, should error and prevent next operation
await run_sync_in_worker_thread(
s3_client.copy,
CopySource={"Bucket": source_bucket_name, "Key": source_path},
Bucket=target_bucket_name,
Key=target_path,
)
s3_client.delete_object(Bucket=source_bucket_name, Key=source_path)
return target_path
@async_dispatch(amove_object)
def move_object(
self,
from_path: Union[str, Path],
to_path: Union[str, Path],
to_bucket: Optional[Union["S3Bucket", str]] = None,
) -> str:
"""Uses S3's internal CopyObject and DeleteObject to move objects within or
between buckets. To move objects between buckets, `self`'s credentials must
have permission to read and delete the source object and write to the target
object. If the credentials do not have those permissions, this method will raise
an error. If the credentials have permission to read the source object but not
delete it, the object will be copied but not deleted.
Args:
from_path: The path of the object to move.
to_path: The path to move the object to.
to_bucket: The bucket to move to. Defaults to the current bucket.
Returns:
The path that the object was moved to. Excludes the bucket name.
Examples:
Move notes.txt from my_folder/notes.txt to my_folder/notes_copy.txt.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.move_object("my_folder/notes.txt", "my_folder/notes_copy.txt")
```
Move notes.txt from my_folder/notes.txt to my_folder/notes_copy.txt in
another bucket.
```python
from prefect_aws.s3 import S3Bucket
s3_bucket = S3Bucket.load("my-bucket")
s3_bucket.move_object(
"my_folder/notes.txt",
"my_folder/notes_copy.txt",
to_bucket="other-bucket"
)
```
"""
s3_client = self.credentials.get_s3_client()
(
source_bucket_name,
source_path,
target_bucket_name,
target_path,
) = self._move_object_setup(from_path, to_path, to_bucket)
s3_client.copy(
CopySource={"Bucket": source_bucket_name, "Key": source_path},
Bucket=target_bucket_name,
Key=target_path,
)
s3_client.delete_object(Bucket=source_bucket_name, Key=source_path)
return target_path
|
S3Bucket
|
python
|
pytorch__pytorch
|
torch/ao/quantization/qconfig_mapping.py
|
{
"start": 7665,
"end": 14845
}
|
class ____:
"""
Mapping from model ops to :class:`torch.ao.quantization.QConfig` s.
The user can specify QConfigs using the following methods (in increasing match priority):
``set_global`` : sets the global (default) QConfig
``set_object_type`` : sets the QConfig for a given module type, function, or method name
``set_module_name_regex`` : sets the QConfig for modules matching the given regex string
``set_module_name`` : sets the QConfig for modules matching the given module name
``set_module_name_object_type_order`` : sets the QConfig for modules matching a combination
of the given module name, object type, and the index at which the module appears
Example usage::
qconfig_mapping = QConfigMapping()
.set_global(global_qconfig)
.set_object_type(torch.nn.Linear, qconfig1)
.set_object_type(torch.nn.ReLU, qconfig1)
.set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
.set_module_name_regex("foo.*", qconfig2)
.set_module_name("module1", qconfig1)
.set_module_name("module2", qconfig2)
.set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, qconfig3)
"""
def __init__(self) -> None:
# In increasing match priority:
self.global_qconfig: QConfigAny = None
self.object_type_qconfigs: OrderedDict[Callable | str, QConfigAny] = (
OrderedDict()
)
self.module_name_regex_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
self.module_name_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
self.module_name_object_type_order_qconfigs: OrderedDict[
tuple[str, Callable, int], QConfigAny
] = OrderedDict()
def set_global(self, global_qconfig: QConfigAny) -> QConfigMapping:
"""
Set the global (default) QConfig.
"""
self.global_qconfig = global_qconfig
return self
def set_object_type(
self, object_type: Callable | str, qconfig: QConfigAny
) -> QConfigMapping:
"""
Set the QConfig for a given module type, function, or method name.
If the QConfig for an existing object type was already set, the new QConfig will override the old one.
"""
self.object_type_qconfigs[object_type] = qconfig
return self
def set_module_name_regex(
self, module_name_regex: str, qconfig: QConfigAny
) -> QConfigMapping:
"""
Set the QConfig for modules matching the given regex string.
Regexes will be matched in the order in which they are registered through this method.
Thus, the caller should register more specific patterns first, e.g.::
qconfig_mapping = QConfigMapping()
.set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
.set_module_name_regex("foo.*bar.*", qconfig2)
.set_module_name_regex("foo.*", qconfig3)
In this example, "foo.bar.conv0" would match qconfig1, "foo.bar.linear" would match qconfig2,
and "foo.baz.relu" would match qconfig3.
If the QConfig for an existing module name regex was already set, the new QConfig will override the
old one while preserving the order in which the regexes were originally registered.
"""
self.module_name_regex_qconfigs[module_name_regex] = qconfig
return self
def set_module_name(self, module_name: str, qconfig: QConfigAny) -> QConfigMapping:
"""
Set the QConfig for modules matching the given module name.
If the QConfig for an existing module name was already set, the new QConfig will override the old one.
"""
self.module_name_qconfigs[module_name] = qconfig
return self
def set_module_name_object_type_order(
self, module_name: str, object_type: Callable, index: int, qconfig: QConfigAny
) -> QConfigMapping:
"""
Set the QConfig for modules matching a combination of the given module name, object type,
and the index at which the module appears.
If the QConfig for an existing (module name, object type, index) was already set, the new QConfig
will override the old one.
"""
self.module_name_object_type_order_qconfigs[
(module_name, object_type, index)
] = qconfig
return self
def __repr__(self) -> str:
output = self.__class__.__name__ + " ("
for style_name in _QCONFIG_STYLE_ORDER:
output += f"\n {style_name}"
qconfigs = getattr(self, style_name)
if isinstance(qconfigs, OrderedDict) and len(qconfigs) > 0:
for key, qconfig in qconfigs.items():
output += f"\n {key}: {qconfig}"
else:
output += f"\n {qconfigs}"
return output + "\n)"
# TODO: remove this
def to_dict(self) -> dict[str, Any]:
"""
Convert this ``QConfigMapping`` to a dictionary with the following keys:
"" (for global QConfig)
"object_type"
"module_name_regex"
"module_name"
"module_name_object_type_order"
The values of this dictionary are lists of tuples.
"""
return {
_GLOBAL_DICT_KEY: self.global_qconfig,
_OBJECT_TYPE_DICT_KEY: list(self.object_type_qconfigs.items()),
_MODULE_NAME_REGEX_DICT_KEY: list(self.module_name_regex_qconfigs.items()),
_MODULE_NAME_DICT_KEY: list(self.module_name_qconfigs.items()),
_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY: [
(*k, v) for k, v in self.module_name_object_type_order_qconfigs.items()
],
}
# TODO: remove this
@classmethod
def from_dict(cls, qconfig_dict: dict[str, Any]) -> QConfigMapping:
"""
Create a ``QConfigMapping`` from a dictionary with the following keys (all optional):
"" (for global QConfig)
"object_type"
"module_name_regex"
"module_name"
"module_name_object_type_order"
The values of this dictionary are expected to be lists of tuples.
"""
conf = cls()
if _GLOBAL_DICT_KEY in qconfig_dict:
conf.set_global(qconfig_dict[_GLOBAL_DICT_KEY])
for object_type, qconfig in qconfig_dict.get(_OBJECT_TYPE_DICT_KEY, []):
conf.set_object_type(object_type, qconfig)
for module_name_regex, qconfig in qconfig_dict.get(
_MODULE_NAME_REGEX_DICT_KEY, []
):
conf.set_module_name_regex(module_name_regex, qconfig)
for module_name, qconfig in qconfig_dict.get(_MODULE_NAME_DICT_KEY, []):
conf.set_module_name(module_name, qconfig)
for module_name, object_type, index, qconfig in qconfig_dict.get(
_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY, []
):
conf.set_module_name_object_type_order(
module_name, object_type, index, qconfig
)
return conf
|
QConfigMapping
|
python
|
walkccc__LeetCode
|
solutions/2033. Minimum Operations to Make a Uni-Value Grid/2033.py
|
{
"start": 0,
"end": 285
}
|
class ____:
def minOperations(self, grid: list[list[int]], x: int) -> int:
arr = sorted([a for row in grid for a in row])
if any((a - arr[0]) % x for a in arr):
return -1
ans = 0
for a in arr:
ans += abs(a - arr[len(arr) // 2]) // x
return ans
|
Solution
|
python
|
ipython__ipython
|
IPython/core/display.py
|
{
"start": 20455,
"end": 22870
}
|
class ____(JSON):
"""GeoJSON expects JSON-able dict
not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict containers.
"""
def __init__(self, *args, **kwargs):
"""Create a GeoJSON display object given raw data.
Parameters
----------
data : dict or list
VegaLite data. Not an already-serialized JSON string.
Scalar types (None, number, string) are not allowed, only dict
or list containers.
url_template : string
Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template
layer_options : dict
Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the data from.
metadata : dict
Specify extra metadata to attach to the json display object.
Examples
--------
The following will display an interactive map of Mars with a point of
interest on frontend that do support GeoJSON display.
>>> from IPython.display import GeoJSON
>>> GeoJSON(data={
... "type": "Feature",
... "geometry": {
... "type": "Point",
... "coordinates": [-81.327, 296.038]
... }
... },
... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
... layer_options={
... "basemap_id": "celestia_mars-shaded-16k_global",
... "attribution" : "Celestia/praesepe",
... "minZoom" : 0,
... "maxZoom" : 18,
... })
<IPython.core.display.GeoJSON object>
In the terminal IPython, you will only see the text representation of
the GeoJSON object.
"""
super(GeoJSON, self).__init__(*args, **kwargs)
def _ipython_display_(self):
bundle = {
'application/geo+json': self.data,
'text/plain': '<IPython.display.GeoJSON object>'
}
metadata = {
'application/geo+json': self.metadata
}
display_functions.display(bundle, metadata=metadata, raw=True)
|
GeoJSON
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_23/frames.py
|
{
"start": 464689,
"end": 468258
}
|
class ____(Request):
"""
For each passed query return projected frames matcing the conditions.
One frame is returned per unique query field value
:param versions: Dataset versions
:type versions: Sequence[ViewEntry]
:param query: The list of field queries
:type query: Sequence[dict]
"""
_service = "frames"
_action = "get_with_projection"
_version = "2.23"
_schema = {
"definitions": {
"view_entry": {
"properties": {
"dataset": {
"description": "Existing Dataset id",
"type": ["string", "null"],
},
"merge_with": {
"description": "Version ID to merge with",
"type": ["string", "null"],
},
"version": {
"description": "Version id of a version belonging to the dataset",
"type": ["string", "null"],
},
},
"type": "object",
}
},
"properties": {
"query": {
"description": "The list of field queries",
"items": {
"properties": {
"field": {
"description": "The field name",
"type": "string",
},
"projection": {
"description": "List of projected fields",
"items": {"type": "string"},
"type": "array",
},
"values": {
"description": "The allowed field values",
"items": {"type": "string"},
"type": "array",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"versions": {
"description": "Dataset versions",
"items": {"$ref": "#/definitions/view_entry"},
"type": ["array", "null"],
},
},
"required": ["dataview"],
"type": "object",
}
def __init__(self, versions=None, query=None, **kwargs):
super(GetWithProjectionRequest, self).__init__(**kwargs)
self.versions = versions
self.query = query
@schema_property("versions")
def versions(self):
return self._property_versions
@versions.setter
def versions(self, value):
if value is None:
self._property_versions = None
return
self.assert_isinstance(value, "versions", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
ViewEntry.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "versions", ViewEntry, is_array=True)
self._property_versions = value
@schema_property("query")
def query(self):
return self._property_query
@query.setter
def query(self, value):
if value is None:
self._property_query = None
return
self.assert_isinstance(value, "query", (list, tuple))
self.assert_isinstance(value, "query", (dict,), is_array=True)
self._property_query = value
|
GetWithProjectionRequest
|
python
|
huggingface__transformers
|
src/transformers/models/speecht5/modeling_speecht5.py
|
{
"start": 34558,
"end": 35198
}
|
class ____(nn.Module, EmbeddingAccessMixin):
def __init__(self, config):
super().__init__()
self.config = config
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
def forward(self, hidden_states: torch.Tensor):
return self.lm_head(hidden_states)
def get_output_embeddings(self):
# Post-net has no token embeddings, but its lm_head must still be
# tied to the decoder weights when `tie_word_embeddings=True`.
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
|
SpeechT5TextDecoderPostnet
|
python
|
getsentry__sentry
|
tests/sentry/api/helpers/test_group_index.py
|
{
"start": 23325,
"end": 24130
}
|
class ____(TestCase):
def setUp(self) -> None:
self.group = self.create_group()
self.group_list = [self.group]
self.project_lookup = {self.group.project_id: self.group.project}
def test_has_seen(self) -> None:
handle_has_seen(True, self.group_list, self.project_lookup, [self.project], self.user)
assert GroupSeen.objects.filter(group=self.group, user_id=self.user.id).exists()
def test_not_has_seen(self) -> None:
GroupSeen.objects.create(
group=self.group, user_id=self.user.id, project_id=self.group.project_id
)
handle_has_seen(False, self.group_list, self.project_lookup, [self.project], self.user)
assert not GroupSeen.objects.filter(group=self.group, user_id=self.user.id).exists()
|
TestHandleHasSeen
|
python
|
django__django
|
tests/delete_regress/models.py
|
{
"start": 1438,
"end": 1805
}
|
class ____(models.Model):
contacts = models.ManyToManyField(Contact, related_name="research_contacts")
primary_contact = models.ForeignKey(
Contact, models.SET_NULL, null=True, related_name="primary_contacts"
)
secondary_contact = models.ForeignKey(
Contact, models.SET_NULL, null=True, related_name="secondary_contacts"
)
|
Researcher
|
python
|
apache__airflow
|
providers/amazon/tests/unit/amazon/aws/transfers/test_google_api_to_s3.py
|
{
"start": 1086,
"end": 7610
}
|
class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
models.Connection(
conn_id="google_test",
host="google",
conn_type="google_cloud_platform",
schema="refresh_token",
login="client_id",
password="client_secret",
)
)
create_connection_without_db(
models.Connection(
conn_id="s3_test",
conn_type="s3",
schema="test",
extra='{"aws_access_key_id": "aws_access_key_id", "aws_secret_access_key":'
' "aws_secret_access_key"}',
)
)
self.kwargs = {
"gcp_conn_id": "google_test",
"google_api_service_name": "test_service",
"google_api_service_version": "v3",
"google_api_endpoint_path": "analyticsreporting.reports.batchGet",
"google_api_endpoint_params": {},
"google_api_pagination": False,
"google_api_num_retries": 0,
"aws_conn_id": "s3_test",
"s3_destination_key": "s3://test/google_api_to_s3_test.csv",
"s3_overwrite": True,
"task_id": "task_id",
"dag": None,
}
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.GoogleDiscoveryApiHook.query")
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.S3Hook.load_string")
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.json.dumps")
def test_execute(self, mock_json_dumps, mock_s3_hook_load_string, mock_google_api_hook_query):
context = {"task_instance": Mock()}
GoogleApiToS3Operator(**self.kwargs).execute(context)
mock_google_api_hook_query.assert_called_once_with(
endpoint=self.kwargs["google_api_endpoint_path"],
data=self.kwargs["google_api_endpoint_params"],
paginate=self.kwargs["google_api_pagination"],
num_retries=self.kwargs["google_api_num_retries"],
)
mock_json_dumps.assert_called_once_with(mock_google_api_hook_query.return_value)
mock_s3_hook_load_string.assert_called_once_with(
string_data=mock_json_dumps.return_value,
bucket_name="test",
key="google_api_to_s3_test.csv",
replace=self.kwargs["s3_overwrite"],
)
context["task_instance"].xcom_pull.assert_not_called()
context["task_instance"].xcom_push.assert_not_called()
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.GoogleDiscoveryApiHook.query")
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.S3Hook.load_string")
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.json.dumps")
def test_execute_with_xcom(self, mock_json_dumps, mock_s3_hook_load_string, mock_google_api_hook_query):
context = {"task_instance": Mock()}
xcom_kwargs = {
"google_api_response_via_xcom": "response",
"google_api_endpoint_params_via_xcom": "params",
"google_api_endpoint_params_via_xcom_task_ids": "params",
}
context["task_instance"].xcom_pull.return_value = {}
GoogleApiToS3Operator(**self.kwargs, **xcom_kwargs).execute(context)
mock_google_api_hook_query.assert_called_once_with(
endpoint=self.kwargs["google_api_endpoint_path"],
data=self.kwargs["google_api_endpoint_params"],
paginate=self.kwargs["google_api_pagination"],
num_retries=self.kwargs["google_api_num_retries"],
)
mock_json_dumps.assert_called_once_with(mock_google_api_hook_query.return_value)
mock_s3_hook_load_string.assert_called_once_with(
string_data=mock_json_dumps.return_value,
bucket_name="test",
key="google_api_to_s3_test.csv",
replace=self.kwargs["s3_overwrite"],
)
context["task_instance"].xcom_pull.assert_called_once_with(
task_ids=xcom_kwargs["google_api_endpoint_params_via_xcom_task_ids"],
key=xcom_kwargs["google_api_endpoint_params_via_xcom"],
)
context["task_instance"].xcom_push.assert_called_once_with(
key=xcom_kwargs["google_api_response_via_xcom"], value=mock_google_api_hook_query.return_value
)
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.GoogleDiscoveryApiHook.query")
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.S3Hook.load_string")
@patch("airflow.providers.amazon.aws.transfers.google_api_to_s3.json.dumps")
@patch(
"airflow.providers.amazon.aws.transfers.google_api_to_s3.sys.getsizeof", return_value=MAX_XCOM_SIZE
)
def test_execute_with_xcom_exceeded_max_xcom_size(
self, mock_sys_getsizeof, mock_json_dumps, mock_s3_hook_load_string, mock_google_api_hook_query
):
context = {"task_instance": Mock()}
xcom_kwargs = {
"google_api_response_via_xcom": "response",
"google_api_endpoint_params_via_xcom": "params",
"google_api_endpoint_params_via_xcom_task_ids": "params",
}
context["task_instance"].xcom_pull.return_value = {}
with pytest.raises(RuntimeError):
GoogleApiToS3Operator(**self.kwargs, **xcom_kwargs).execute(context)
mock_google_api_hook_query.assert_called_once_with(
endpoint=self.kwargs["google_api_endpoint_path"],
data=self.kwargs["google_api_endpoint_params"],
paginate=self.kwargs["google_api_pagination"],
num_retries=self.kwargs["google_api_num_retries"],
)
mock_json_dumps.assert_called_once_with(mock_google_api_hook_query.return_value)
mock_s3_hook_load_string.assert_called_once_with(
string_data=mock_json_dumps.return_value,
bucket_name="test",
key="google_api_to_s3_test.csv",
replace=self.kwargs["s3_overwrite"],
)
context["task_instance"].xcom_pull.assert_called_once_with(
task_ids=xcom_kwargs["google_api_endpoint_params_via_xcom_task_ids"],
key=xcom_kwargs["google_api_endpoint_params_via_xcom"],
)
context["task_instance"].xcom_push.assert_not_called()
mock_sys_getsizeof.assert_called_once_with(mock_google_api_hook_query.return_value)
|
TestGoogleApiToS3
|
python
|
openai__openai-python
|
src/openai/types/beta/threads/message_deleted.py
|
{
"start": 192,
"end": 303
}
|
class ____(BaseModel):
id: str
deleted: bool
object: Literal["thread.message.deleted"]
|
MessageDeleted
|
python
|
huggingface__transformers
|
tests/models/siglip2/test_modeling_siglip2.py
|
{
"start": 20944,
"end": 23979
}
|
class ____(Siglip2ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (Siglip2Model,) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": Siglip2Model} if is_torch_available() else {}
additional_model_inputs = [
"pixel_values",
"pixel_attention_mask",
"spatial_shapes",
]
test_resize_embeddings = False
test_attention_outputs = False
# MP works but offload doesn't work when the MultiheadAttention is offloaded
# TODO: One potential solution would be to add to set preload_module_classes = ["Siglip2MultiheadAttentionPoolingHead"]
# in the dispatch_model function
test_cpu_offload = False
test_disk_offload_safetensors = False
test_disk_offload_bin = False
_is_composite = True
def setUp(self):
self.model_tester = Siglip2ModelTester(self)
self.config_tester = ConfigTester(self, config_class=Siglip2Config, has_text_modality=False)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@unittest.skip(reason="Hidden_states is tested in individual model tests")
def test_hidden_states_output(self):
pass
@unittest.skip(reason="Inputs_embeds is tested in individual model tests")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="Retain_grad is tested in individual model tests")
def test_retain_grad_hidden_states_attentions(self):
pass
@unittest.skip(reason="Siglip2Model does not have input/output embeddings")
def test_model_get_set_embeddings(self):
pass
def test_load_vision_text_config(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
# Save Siglip2Config and check if we can load Siglip2VisionConfig from it
with tempfile.TemporaryDirectory() as tmp_dir_name:
config.save_pretrained(tmp_dir_name)
vision_config = Siglip2VisionConfig.from_pretrained(tmp_dir_name)
self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
# Save Siglip2Config and check if we can load Siglip2TextConfig from it
with tempfile.TemporaryDirectory() as tmp_dir_name:
config.save_pretrained(tmp_dir_name)
text_config = Siglip2TextConfig.from_pretrained(tmp_dir_name)
self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
@slow
def test_model_from_pretrained(self):
model_name = "google/siglip2-base-patch16-naflex"
model = Siglip2Model.from_pretrained(model_name)
self.assertIsNotNone(model)
@require_flash_attn
@require_torch_gpu
@mark.flash_attn_test
def test_flash_attn_2_inference_equivalence_right_padding(self):
self.skipTest("Siglip2 does not support right padding")
|
Siglip2ModelTest
|
python
|
Netflix__metaflow
|
metaflow/datastore/spin_datastore.py
|
{
"start": 129,
"end": 3035
}
|
class ____(object):
def __init__(
self,
flow_name: str,
run_id: str,
step_name: str,
task_id: str,
orig_datastore: TaskDataStore,
spin_artifacts: Dict[str, Any],
):
"""
SpinTaskDatastore is a datastore for a task that is used to retrieve
artifacts and attributes for a spin step. It uses the task pathspec
from a previous execution of the step to access the artifacts and attributes.
Parameters:
-----------
flow_name : str
Name of the flow
run_id : str
Run ID of the flow
step_name : str
Name of the step
task_id : str
Task ID of the step
orig_datastore : TaskDataStore
The datastore for the underlying task that is being spun.
spin_artifacts : Dict[str, Any]
User provided artifacts that are to be used in the spin task. This is a dictionary
where keys are artifact names and values are the actual data or metadata.
"""
self.flow_name = flow_name
self.run_id = run_id
self.step_name = step_name
self.task_id = task_id
self.orig_datastore = orig_datastore
self.spin_artifacts = spin_artifacts
self._task = None
# Update _objects and _info in order to persist artifacts
# See `persist` method in `TaskDatastore` for more details
self._objects = self.orig_datastore._objects.copy()
self._info = self.orig_datastore._info.copy()
# We strip out some of the control ones
for key in ("_transition",):
if key in self._objects:
del self._objects[key]
del self._info[key]
from_start("SpinTaskDatastore: Initialized artifacts")
@require_mode(None)
def __getitem__(self, name):
try:
# Check if it's an artifact in the spin_artifacts
return self.spin_artifacts[name]
except KeyError:
try:
# Check if it's an attribute of the task
# _foreach_stack, _foreach_index, ...
return self.orig_datastore[name]
except (KeyError, AttributeError) as e:
raise KeyError(
f"Attribute '{name}' not found in the previous execution "
f"of the tasks for `{self.step_name}`."
) from e
@require_mode(None)
def is_none(self, name):
val = self.__getitem__(name)
return val is None
@require_mode(None)
def __contains__(self, name):
try:
_ = self.__getitem__(name)
return True
except KeyError:
return False
@require_mode(None)
def items(self):
if self._objects:
return self._objects.items()
return {}
|
SpinTaskDatastore
|
python
|
aio-libs__aiohttp
|
aiohttp/web_exceptions.py
|
{
"start": 9405,
"end": 9474
}
|
class ____(HTTPClientError):
status_code = 424
|
HTTPFailedDependency
|
python
|
pallets__markupsafe
|
src/markupsafe/__init__.py
|
{
"start": 11088,
"end": 12090
}
|
class ____(string.Formatter):
__slots__ = ("escape",)
def __init__(self, escape: _TPEscape) -> None:
self.escape: _TPEscape = escape
super().__init__()
def format_field(self, value: t.Any, format_spec: str) -> str:
if hasattr(value, "__html_format__"):
rv = value.__html_format__(format_spec)
elif hasattr(value, "__html__"):
if format_spec:
raise ValueError(
f"Format specifier {format_spec} given, but {type(value)} does not"
" define __html_format__. A class that defines __html__ must define"
" __html_format__ to work with format specifiers."
)
rv = value.__html__()
else:
# We need to make sure the format spec is str here as
# otherwise the wrong callback methods are invoked.
rv = super().format_field(value, str(format_spec))
return str(self.escape(rv))
|
EscapeFormatter
|
python
|
kamyu104__LeetCode-Solutions
|
Python/kth-smallest-number-in-multiplication-table.py
|
{
"start": 42,
"end": 545
}
|
class ____(object):
def findKthNumber(self, m, n, k):
"""
:type m: int
:type n: int
:type k: int
:rtype: int
"""
def count(target, m, n):
return sum(min(target//i, n) for i in xrange(1, m+1))
left, right = 1, m*n
while left <= right:
mid = left + (right-left)/2
if count(mid, m, n) >= k:
right = mid-1
else:
left = mid+1
return left
|
Solution
|
python
|
Delgan__loguru
|
tests/exceptions/source/diagnose/multilines_repr.py
|
{
"start": 138,
"end": 341
}
|
class ____:
def __repr__(self):
return "[[1, 2, 3]\n" " [4, 5, 6]\n" " [7, 8, 9]]"
def multiline():
a = b = A()
a + b
try:
multiline()
except TypeError:
logger.exception("")
|
A
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_set_column01.py
|
{
"start": 315,
"end": 2148
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_column01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("A:Z", 0.08) # Test that the cols are overridden.
worksheet.set_column("B:B", 0.17)
worksheet.set_column("C:C", 0.25)
worksheet.set_column("D:D", 0.33)
worksheet.set_column("E:E", 0.42)
worksheet.set_column("F:F", 0.5)
worksheet.set_column("G:G", 0.58)
worksheet.set_column("H:H", 0.67)
worksheet.set_column("I:I", 0.75)
worksheet.set_column("J:J", 0.83)
worksheet.set_column("K:K", 0.92)
worksheet.set_column("L:L", 1)
worksheet.set_column("M:M", 1.14)
worksheet.set_column("N:N", 1.29)
worksheet.set_column("O:O", 1.43)
worksheet.set_column("P:P", 1.57)
worksheet.set_column("Q:Q", 1.71)
worksheet.set_column("R:R", 1.86)
worksheet.set_column("S:S", 2)
worksheet.set_column("T:T", 2.14)
worksheet.set_column("U:U", 2.29)
worksheet.set_column("V:V", 2.43)
worksheet.set_column("W:W", 2.57)
worksheet.set_column("X:X", 2.71)
worksheet.set_column("Y:Y", 2.86)
worksheet.set_column("Z:Z", 3)
worksheet.set_column("AB:AB", 8.57)
worksheet.set_column("AC:AC", 8.71)
worksheet.set_column("AD:AD", 8.86)
worksheet.set_column("AE:AE", 9)
worksheet.set_column("AF:AF", 9.14)
worksheet.set_column("AG:AG", 9.29)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/assignment5.py
|
{
"start": 148,
"end": 354
}
|
class ____:
key: str
next: Optional["Node"] = None
node = Node()
# This should analyze fine because node.next should be assigned
# None before node is assigned None.
node.next, node = None, None
|
Node
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/core_api/datamodels/plugins.py
|
{
"start": 4371,
"end": 4553
}
|
class ____(BaseModel):
"""Plugin Import Error Collection serializer."""
import_errors: list[PluginImportErrorResponse]
total_entries: int
|
PluginImportErrorCollectionResponse
|
python
|
django__django
|
tests/test_client/views.py
|
{
"start": 6632,
"end": 9536
}
|
class ____(Form):
text = fields.CharField()
email = fields.EmailField()
value = fields.IntegerField()
single = fields.ChoiceField(choices=TestChoices)
multi = fields.MultipleChoiceField(choices=TestChoices)
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get("text") == "Raise non-field error":
raise ValidationError("Non-field error.")
return cleaned_data
def form_view(request):
"A view that tests a simple form"
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
t = Template("Valid POST data.", name="Valid POST Template")
c = Context()
else:
t = Template(
"Invalid POST data. {{ form.errors }}", name="Invalid POST Template"
)
c = Context({"form": form})
else:
form = TestForm(request.GET)
t = Template("Viewing base form. {{ form }}.", name="Form GET Template")
c = Context({"form": form})
return HttpResponse(t.render(c))
def form_view_with_template(request):
"A view that tests a simple form"
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
message = "POST data OK"
else:
message = "POST data has errors"
else:
form = TestForm()
message = "GET form page"
return render(
request,
"form_view.html",
{
"form": form,
"message": message,
},
)
@login_required
def login_protected_view(request):
"A simple view that is login protected."
t = Template(
"This is a login protected test. Username is {{ user.username }}.",
name="Login Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
@login_required(redirect_field_name="redirect_to")
def login_protected_view_changed_redirect(request):
"A simple view that is login protected with a custom redirect field set"
t = Template(
"This is a login protected test. Username is {{ user.username }}.",
name="Login Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
def _permission_protected_view(request):
"A simple view that is permission protected."
t = Template(
"This is a permission protected test. "
"Username is {{ user.username }}. "
"Permissions are {{ user.get_all_permissions }}.",
name="Permissions Template",
)
c = Context({"user": request.user})
return HttpResponse(t.render(c))
permission_protected_view = permission_required("permission_not_granted")(
_permission_protected_view
)
permission_protected_view_exception = permission_required(
"permission_not_granted", raise_exception=True
)(_permission_protected_view)
|
TestForm
|
python
|
pytest-dev__pytest
|
testing/test_pluginmanager.py
|
{
"start": 8667,
"end": 14846
}
|
class ____:
def test_register_imported_modules(self) -> None:
pm = PytestPluginManager()
mod = types.ModuleType("x.y.pytest_hello")
pm.register(mod)
assert pm.is_registered(mod)
values = pm.get_plugins()
assert mod in values
pytest.raises(ValueError, pm.register, mod)
pytest.raises(ValueError, lambda: pm.register(mod))
# assert not pm.is_registered(mod2)
assert pm.get_plugins() == values
def test_canonical_import(self, monkeypatch):
mod = types.ModuleType("pytest_xyz")
monkeypatch.setitem(sys.modules, "pytest_xyz", mod)
pm = PytestPluginManager()
pm.import_plugin("pytest_xyz")
assert pm.get_plugin("pytest_xyz") == mod
assert pm.is_registered(mod)
def test_consider_module(
self, pytester: Pytester, pytestpm: PytestPluginManager
) -> None:
pytester.syspathinsert()
pytester.makepyfile(pytest_p1="#")
pytester.makepyfile(pytest_p2="#")
mod = types.ModuleType("temp")
mod.__dict__["pytest_plugins"] = ["pytest_p1", "pytest_p2"]
pytestpm.consider_module(mod)
p1 = pytestpm.get_plugin("pytest_p1")
assert p1 is not None
assert p1.__name__ == "pytest_p1"
p2 = pytestpm.get_plugin("pytest_p2")
assert p2 is not None
assert p2.__name__ == "pytest_p2"
def test_consider_module_import_module(
self, pytester: Pytester, _config_for_test: Config
) -> None:
pytestpm = _config_for_test.pluginmanager
mod = types.ModuleType("x")
mod.__dict__["pytest_plugins"] = "pytest_a"
aplugin = pytester.makepyfile(pytest_a="#")
reprec = pytester.make_hook_recorder(pytestpm)
pytester.syspathinsert(aplugin.parent)
pytestpm.consider_module(mod)
call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)
assert call.plugin.__name__ == "pytest_a"
# check that it is not registered twice
pytestpm.consider_module(mod)
values = reprec.getcalls("pytest_plugin_registered")
assert len(values) == 1
def test_consider_env_fails_to_import(
self, monkeypatch: MonkeyPatch, pytestpm: PytestPluginManager
) -> None:
monkeypatch.setenv("PYTEST_PLUGINS", "nonexisting", prepend=",")
with pytest.raises(ImportError):
pytestpm.consider_env()
@pytest.mark.filterwarnings("always")
def test_plugin_skip(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
p = pytester.makepyfile(
skipping1="""
import pytest
pytest.skip("hello", allow_module_level=True)
"""
)
shutil.copy(p, p.with_name("skipping2.py"))
monkeypatch.setenv("PYTEST_PLUGINS", "skipping2")
result = pytester.runpytest("-p", "skipping1", syspathinsert=True)
assert result.ret == ExitCode.NO_TESTS_COLLECTED
result.stdout.fnmatch_lines(
["*skipped plugin*skipping1*hello*", "*skipped plugin*skipping2*hello*"]
)
def test_consider_env_plugin_instantiation(
self,
pytester: Pytester,
monkeypatch: MonkeyPatch,
pytestpm: PytestPluginManager,
) -> None:
pytester.syspathinsert()
pytester.makepyfile(xy123="#")
monkeypatch.setitem(os.environ, "PYTEST_PLUGINS", "xy123")
l1 = len(pytestpm.get_plugins())
pytestpm.consider_env()
l2 = len(pytestpm.get_plugins())
assert l2 == l1 + 1
assert pytestpm.get_plugin("xy123")
pytestpm.consider_env()
l3 = len(pytestpm.get_plugins())
assert l2 == l3
def test_pluginmanager_ENV_startup(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
pytester.makepyfile(pytest_x500="#")
p = pytester.makepyfile(
"""
import pytest
def test_hello(pytestconfig):
plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')
assert plugin is not None
"""
)
monkeypatch.setenv("PYTEST_PLUGINS", "pytest_x500", prepend=",")
result = pytester.runpytest(p, syspathinsert=True)
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_import_plugin_importname(
self, pytester: Pytester, pytestpm: PytestPluginManager
) -> None:
pytest.raises(ImportError, pytestpm.import_plugin, "qweqwex.y")
pytest.raises(ImportError, pytestpm.import_plugin, "pytest_qweqwx.y")
pytester.syspathinsert()
pluginname = "pytest_hello"
pytester.makepyfile(**{pluginname: ""})
pytestpm.import_plugin("pytest_hello")
len1 = len(pytestpm.get_plugins())
pytestpm.import_plugin("pytest_hello")
len2 = len(pytestpm.get_plugins())
assert len1 == len2
plugin1 = pytestpm.get_plugin("pytest_hello")
assert plugin1 is not None
assert plugin1.__name__.endswith("pytest_hello")
plugin2 = pytestpm.get_plugin("pytest_hello")
assert plugin2 is plugin1
def test_import_plugin_dotted_name(
self, pytester: Pytester, pytestpm: PytestPluginManager
) -> None:
pytest.raises(ImportError, pytestpm.import_plugin, "qweqwex.y")
pytest.raises(ImportError, pytestpm.import_plugin, "pytest_qweqwex.y")
pytester.syspathinsert()
pytester.mkpydir("pkg").joinpath("plug.py").write_text("x=3", encoding="utf-8")
pluginname = "pkg.plug"
pytestpm.import_plugin(pluginname)
mod = pytestpm.get_plugin("pkg.plug")
assert mod is not None
assert mod.x == 3
def test_consider_conftest_deps(
self,
pytester: Pytester,
pytestpm: PytestPluginManager,
) -> None:
mod = import_path(
pytester.makepyfile("pytest_plugins='xyz'"),
root=pytester.path,
consider_namespace_packages=False,
)
with pytest.raises(ImportError):
pytestpm.consider_conftest(mod, registration_name="unused")
|
TestPytestPluginManager
|
python
|
google__flatbuffers
|
tests/namespace_test/NamespaceA/SecondTableInA.py
|
{
"start": 181,
"end": 1515
}
|
class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = SecondTableInA()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsSecondTableInA(cls, buf, offset=0):
"""This method is deprecated. Please switch to GetRootAs."""
return cls.GetRootAs(buf, offset)
# SecondTableInA
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# SecondTableInA
def ReferToC(self):
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
if o != 0:
x = self._tab.Indirect(o + self._tab.Pos)
obj = TableInC()
obj.Init(self._tab.Bytes, x)
return obj
return None
def SecondTableInAStart(builder):
builder.StartObject(1)
def Start(builder):
return SecondTableInAStart(builder)
def SecondTableInAAddReferToC(builder, referToC):
builder.PrependUOffsetTRelativeSlot(
0, flatbuffers.number_types.UOffsetTFlags.py_type(referToC), 0
)
def AddReferToC(builder, referToC):
return SecondTableInAAddReferToC(builder, referToC)
def SecondTableInAEnd(builder):
return builder.EndObject()
def End(builder):
return SecondTableInAEnd(builder)
try:
from typing import Optional
except:
pass
|
SecondTableInA
|
python
|
scipy__scipy
|
scipy/sparse/linalg/_dsolve/tests/test_linsolve.py
|
{
"start": 28946,
"end": 34644
}
|
class ____:
def setup_method(self):
use_solver(useUmfpack=False)
@pytest.mark.parametrize("fmt",["csr","csc"])
def test_zero_diagonal(self,fmt):
n = 5
rng = np.random.default_rng(43876432987)
A = rng.standard_normal((n, n))
b = np.arange(n)
A = scipy.sparse.tril(A, k=0, format=fmt)
x = spsolve_triangular(A, b, unit_diagonal=True, lower=True)
A.setdiag(1)
assert_allclose(A.dot(x), b)
# Regression test from gh-15199
A = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]], dtype=np.float64)
b = np.array([1., 2., 3.])
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", "CSC or CSR matrix format is", SparseEfficiencyWarning)
spsolve_triangular(A, b, unit_diagonal=True)
@pytest.mark.parametrize("fmt",["csr","csc"])
def test_singular(self,fmt):
n = 5
if fmt == "csr":
A = csr_array((n, n))
else:
A = csc_array((n, n))
b = np.arange(n)
for lower in (True, False):
assert_raises(scipy.linalg.LinAlgError,
spsolve_triangular, A, b, lower=lower)
def test_bad_shape(self):
with warnings.catch_warnings():
warnings.simplefilter("ignore", SparseEfficiencyWarning)
# A is not square.
A = np.zeros((3, 4))
b = ones((4, 1))
assert_raises(ValueError, spsolve_triangular, A, b)
# A2 and b2 have incompatible shapes.
A2 = csr_array(eye(3))
b2 = array([1.0, 2.0])
assert_raises(ValueError, spsolve_triangular, A2, b2)
def test_input_types(self):
with warnings.catch_warnings():
warnings.simplefilter("ignore", SparseEfficiencyWarning)
A = array([[1., 0.], [1., 2.]])
b = array([[2., 0.], [2., 2.]])
for matrix_type in (array, csc_array, csr_array):
x = spsolve_triangular(matrix_type(A), b, lower=True)
assert_array_almost_equal(A.dot(x), b)
@pytest.mark.slow
@pytest.mark.parametrize("n", [10, 10**2, 10**3])
@pytest.mark.parametrize("m", [1, 10])
@pytest.mark.parametrize("lower", [True, False])
@pytest.mark.parametrize("format", ["csr", "csc"])
@pytest.mark.parametrize("unit_diagonal", [False, True])
@pytest.mark.parametrize("choice_of_A", ["real", "complex"])
@pytest.mark.parametrize("choice_of_b", ["floats", "ints", "complexints"])
def test_random(self, n, m, lower, format, unit_diagonal, choice_of_A, choice_of_b):
with warnings.catch_warnings():
warnings.simplefilter("ignore", SparseEfficiencyWarning)
def random_triangle_matrix(n, lower=True, format="csr", choice_of_A="real"):
if choice_of_A == "real":
dtype = np.float64
elif choice_of_A == "complex":
dtype = np.complex128
else:
raise ValueError("choice_of_A must be 'real' or 'complex'.")
rng = np.random.default_rng(789002319)
rvs = rng.random
A = scipy.sparse.random(n, n, density=0.1, format='lil', dtype=dtype,
random_state=rng, data_rvs=rvs)
if lower:
A = scipy.sparse.tril(A, format="lil")
else:
A = scipy.sparse.triu(A, format="lil")
for i in range(n):
A[i, i] = np.random.rand() + 1
if format == "csc":
A = A.tocsc(copy=False)
else:
A = A.tocsr(copy=False)
return A
rng = np.random.default_rng(1234)
A = random_triangle_matrix(n, lower=lower)
if choice_of_b == "floats":
b = rng.random((n, m))
elif choice_of_b == "ints":
b = rng.integers(-9, 9, (n, m))
elif choice_of_b == "complexints":
b = rng.integers(-9, 9, (n, m)) + rng.integers(-9, 9, (n, m)) * 1j
else:
raise ValueError(
"choice_of_b must be 'floats', 'ints', or 'complexints'.")
x = spsolve_triangular(A, b, lower=lower, unit_diagonal=unit_diagonal)
if unit_diagonal:
A.setdiag(1)
assert_allclose(A.dot(x), b, atol=1.5e-6)
@pytest.mark.parametrize("nnz", [10, 10**2, 10**3])
@pytest.mark.parametrize("fmt", ["csr", "csc", "coo", "dia", "dok", "lil"])
def test_is_sptriangular_and_spbandwidth(nnz, fmt):
with warnings.catch_warnings():
warnings.simplefilter('ignore', SparseEfficiencyWarning)
rng = np.random.default_rng(42)
N = nnz // 2
dens = 0.1
A = scipy.sparse.random_array((N, N), density=dens, format="csr", rng=rng)
A[1, 3] = A[3, 1] = 22 # ensure not upper or lower
A = A.asformat(fmt)
AU = scipy.sparse.triu(A, format=fmt)
AL = scipy.sparse.tril(A, format=fmt)
D = 0.1 * scipy.sparse.eye_array(N, format=fmt)
assert is_sptriangular(A) == (False, False)
assert is_sptriangular(AL) == (True, False)
assert is_sptriangular(AU) == (False, True)
assert is_sptriangular(D) == (True, True)
assert spbandwidth(A) == scipy.linalg.bandwidth(A.toarray())
assert spbandwidth(AU) == scipy.linalg.bandwidth(AU.toarray())
assert spbandwidth(AL) == scipy.linalg.bandwidth(AL.toarray())
assert spbandwidth(D) == scipy.linalg.bandwidth(D.toarray())
|
TestSpsolveTriangular
|
python
|
walkccc__LeetCode
|
solutions/47. Permutations II/47.py
|
{
"start": 0,
"end": 556
}
|
class ____:
def permuteUnique(self, nums: list[int]) -> list[list[int]]:
ans = []
used = [False] * len(nums)
def dfs(path: list[int]) -> None:
if len(path) == len(nums):
ans.append(path.copy())
return
for i, num in enumerate(nums):
if used[i]:
continue
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(num)
dfs(path)
path.pop()
used[i] = False
nums.sort()
dfs([])
return ans
|
Solution
|
python
|
tensorflow__tensorflow
|
tensorflow/python/data/experimental/ops/grouping.py
|
{
"start": 16140,
"end": 17164
}
|
class ____:
"""A reducer is used for reducing a set of elements.
A reducer is represented as a tuple of the three functions:
- init_func - to define initial value: key => initial state
- reducer_func - operation to perform on values with same key: (old state, input) => new state
- finalize_func - value to return in the end: state => result
For example,
```
def init_func(_):
return (0.0, 0.0)
def reduce_func(state, value):
return (state[0] + value['features'], state[1] + 1)
def finalize_func(s, n):
return s / n
reducer = tf.data.experimental.Reducer(init_func, reduce_func, finalize_func)
```
"""
def __init__(self, init_func, reduce_func, finalize_func):
self._init_func = init_func
self._reduce_func = reduce_func
self._finalize_func = finalize_func
@property
def init_func(self):
return self._init_func
@property
def reduce_func(self):
return self._reduce_func
@property
def finalize_func(self):
return self._finalize_func
|
Reducer
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/dataclassKwOnly1.py
|
{
"start": 320,
"end": 544
}
|
class ____:
b: int = field(kw_only=True, default=3)
a: str
DC2("hi")
DC2(a="hi")
DC2(a="hi", b=1)
DC2("hi", b=1)
# This should generate an error because "b" is keyword-only.
DC2("hi", 1)
@dataclass(kw_only=True)
|
DC2
|
python
|
django__django
|
django/contrib/staticfiles/management/commands/runserver.py
|
{
"start": 184,
"end": 1373
}
|
class ____(RunserverCommand):
help = (
"Starts a lightweight web server for development and also serves static files."
)
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--nostatic",
action="store_false",
dest="use_static_handler",
help="Tells Django to NOT automatically serve static files at STATIC_URL.",
)
parser.add_argument(
"--insecure",
action="store_true",
dest="insecure_serving",
help="Allows serving static files even if DEBUG is False.",
)
def get_handler(self, *args, **options):
"""
Return the static files serving handler wrapping the default handler,
if static files should be served. Otherwise return the default handler.
"""
handler = super().get_handler(*args, **options)
use_static_handler = options["use_static_handler"]
insecure_serving = options["insecure_serving"]
if use_static_handler and (settings.DEBUG or insecure_serving):
return StaticFilesHandler(handler)
return handler
|
Command
|
python
|
langchain-ai__langchain
|
libs/langchain/tests/integration_tests/cache/fake_embeddings.py
|
{
"start": 2462,
"end": 3469
}
|
class ____(Embeddings):
"""From angles (as strings in units of pi) to unit embedding vectors on a circle."""
def embed_documents(self, texts: list[str]) -> list[list[float]]:
"""Make a list of texts into a list of embedding vectors."""
return [self.embed_query(text) for text in texts]
@override
def embed_query(self, text: str) -> list[float]:
"""Embed query text.
Convert input text to a 'vector' (list of floats).
If the text is a number, use it as the angle for the
unit vector in units of pi.
Any other input text becomes the singular result [0, 0] !
Args:
text: Text to embed.
Returns:
Embedding.
"""
try:
angle = float(text)
return [math.cos(angle * math.pi), math.sin(angle * math.pi)]
except ValueError:
# Assume: just test string, no attention is paid to values.
return [0.0, 0.0]
|
AngularTwoDimensionalEmbeddings
|
python
|
pydantic__pydantic
|
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py
|
{
"start": 1496,
"end": 1682
}
|
class ____(BaseModel, extra='forbid'):
pass
KwargsForbidExtraModel(x=1)
# MYPY: error: Unexpected keyword argument "x" for "KwargsForbidExtraModel" [call-arg]
|
KwargsForbidExtraModel
|
python
|
Pylons__pyramid
|
src/pyramid/predicates.py
|
{
"start": 1497,
"end": 2489
}
|
class ____:
def __init__(self, val, config):
val = as_sorted_tuple(val)
reqs = []
for p in val:
k = p
v = None
if p.startswith('='):
if '=' in p[1:]:
k, v = p[1:].split('=', 1)
k = '=' + k
k, v = k.strip(), v.strip()
elif '=' in p:
k, v = p.split('=', 1)
k, v = k.strip(), v.strip()
reqs.append((k, v))
self.val = val
self.reqs = reqs
def text(self):
return 'request_param %s' % ','.join(
[f'{x}={y}' if y else x for x, y in self.reqs]
)
phash = text
def __call__(self, context, request):
for k, v in self.reqs:
actual = request.params.get(k)
if actual is None:
return False
if v is not None and actual != v:
return False
return True
|
RequestParamPredicate
|
python
|
tensorflow__tensorflow
|
tensorflow/python/distribute/distribute_lib.py
|
{
"start": 31822,
"end": 32506
}
|
class ____(enum.Enum):
"""Replication mode for input function.
* `PER_WORKER`: The input function will be called on each worker
independently, creating as many input pipelines as number of workers.
Replicas will dequeue from the local Dataset on their worker.
`tf.distribute.Strategy` doesn't manage any state sharing between such
separate input pipelines.
* `PER_REPLICA`: The input function will be called on each replica separately.
`tf.distribute.Strategy` doesn't manage any state sharing between such
separate input pipelines.
"""
PER_WORKER = "PER_WORKER"
PER_REPLICA = "PER_REPLICA"
@tf_export("distribute.InputContext")
|
InputReplicationMode
|
python
|
huggingface__transformers
|
src/transformers/models/data2vec/modular_data2vec_audio.py
|
{
"start": 9036,
"end": 9326
}
|
class ____(Wav2Vec2ForXVector):
pass
__all__ = [
"Data2VecAudioForAudioFrameClassification",
"Data2VecAudioForCTC",
"Data2VecAudioForSequenceClassification",
"Data2VecAudioForXVector",
"Data2VecAudioModel",
"Data2VecAudioPreTrainedModel",
]
|
Data2VecAudioForXVector
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/ext/hybrid.py
|
{
"start": 43762,
"end": 43854
}
|
class ____(Protocol[_T_co]):
def __call__(s, self: Any, /) -> None: ...
|
_HybridDeleterType
|
python
|
pydata__xarray
|
xarray/tests/test_backends.py
|
{
"start": 11655,
"end": 12406
}
|
class ____:
def test_robust_getitem(self) -> None:
class UnreliableArrayFailure(Exception):
pass
class UnreliableArray:
def __init__(self, array, failures=1):
self.array = array
self.failures = failures
def __getitem__(self, key):
if self.failures > 0:
self.failures -= 1
raise UnreliableArrayFailure
return self.array[key]
array = UnreliableArray([0])
with pytest.raises(UnreliableArrayFailure):
array[0]
assert array[0] == 0
actual = robust_getitem(array, 0, catch=UnreliableArrayFailure, initial_delay=0)
assert actual == 0
|
TestCommon
|
python
|
facebook__pyre-check
|
tools/generate_taint_models/model.py
|
{
"start": 5133,
"end": 6273
}
|
class ____(RawCallableModel):
callable_object: Callable[..., object]
def __init__(
self,
callable_object: Callable[..., object],
parameter_annotation: Optional[ParameterAnnotation] = None,
returns: Optional[str] = None,
parameter_type_whitelist: Optional[Iterable[str]] = None,
parameter_name_whitelist: Optional[Set[str]] = None,
annotations: Optional[AnnotationSpecification] = None,
whitelist: Optional[WhitelistSpecification] = None,
) -> None:
self.callable_object = callable_object
super().__init__(
parameter_annotation=parameter_annotation,
returns=returns,
parameter_type_whitelist=parameter_type_whitelist,
parameter_name_whitelist=parameter_name_whitelist,
annotations=annotations,
whitelist=whitelist,
)
def _generate_parameters(self) -> List[Parameter]:
return extract_parameters(self.callable_object)
def _get_fully_qualified_callable_name(self) -> Optional[str]:
return extract_qualified_name(self.callable_object)
|
CallableModel
|
python
|
pyparsing__pyparsing
|
examples/infix_math_parser.py
|
{
"start": 965,
"end": 6486
}
|
class ____:
"""A class for defining an infix notation parsers."""
# Supported infix binary operators, i.e., '1+1'. The key is the notation of the operator in infix format,
# and the value the notation in parsed format.
BINARY_OPERATORS: dict[str, str] = {
"+": "Add",
"-": "Subtract",
"*": "Multiply",
"/": "Divide",
"**": "Power",
}
# Supported infix unary operators, i.e., 'Cos(90)'. The key is the notation of the operator in infix format,
# and the value the notation in parsed format.
UNARY_OPERATORS: dict[str, str] = {
"Cos": "Cos",
"Sin": "Sin",
"Tan": "Tan",
"Exp": "Exp",
"Ln": "Ln",
"Lb": "Lb",
"Lg": "Lg",
"LogOnePlus": "LogOnePlus",
"Sqrt": "Sqrt",
"Square": "Square",
"Abs": "Abs",
"Ceil": "Ceil",
"Floor": "Floor",
"Arccos": "Arccos",
"Arccosh": "Arccosh",
"Arcsin": "Arcsin",
"Arcsinh": "Arcsinh",
"Arctan": "Arctan",
"Arctanh": "Arctanh",
"Cosh": "Cosh",
"Sinh": "Sinh",
"Tanh": "Tanh",
"Rational": "Rational",
}
# Supported infix variadic operators (operators that take one or more comma separated arguments),
# i.e., 'Max(1,2, Cos(3)). The key is the notation of the operator in infix format,
# and the value the notation in parsed format.
VARIADIC_OPERATORS: dict[str, str] = {"Max": "Max"}
def __init__(self):
"""A parser for infix notation, e.g., the human readable way of notating mathematical expressions.
The parser can parse infix notation stored in a string. For instance,
"Cos(2 + f_1) - 7.2 + Max(f_2, -f_3)" is parsed to the list:
['Cos', [[2, '+', 'f_1']]], '-', 7.2, '+', ['Max', ['f_2', ['-', 'f_3']].
"""
# Scope limiters
lparen = Suppress("(")
rparen = Suppress(")")
# Define keywords (Note that binary operators must be defined manually)
symbols_variadic = set(InfixExpressionParser.VARIADIC_OPERATORS)
symbols_unary = set(InfixExpressionParser.UNARY_OPERATORS)
# Define binary operation symbols (this is the manual part)
# If new binary operators are to be added, they must be defined here.
signop = one_of("+ -")
multop = one_of("* /")
plusop = one_of("+ -")
expop = Literal("**")
# Dynamically create Keyword objects for variadic functions
variadic_pattern = r"\b(" + f"{'|'.join([*symbols_variadic])}" + r")\b"
variadic_func_names = Regex(variadic_pattern).set_name("variadic function")
# Dynamically create Keyword objects for unary functions
unary_pattern = r"\b(" + f"{'|'.join([*symbols_unary])}" + r")\b"
unary_func_names = Regex(unary_pattern).set_name("unary function")
# Define operands
# Integers
integer = pyparsing_common.integer.set_name("integer")
# Scientific notation
scientific = pyparsing_common.sci_real.set_name("float")
# Complete regex pattern with exclusions and identifier pattern
exclude = f"{'|'.join([*symbols_variadic, *symbols_unary])}"
pattern = r"(?!\b(" + exclude + r")\b)(\b[a-zA-Z_][a-zA-Z0-9_]*\b)"
variable = Regex(pattern).set_name("variable")
operands = variable | scientific | integer
# Forward declarations of variadic and unary function calls
variadic_call = Forward()
unary_call = Forward()
# The parsed expressions are assumed to follow a standard infix syntax. The operands
# of the infix syntax can be either the literal 'operands' defined above (these are singletons),
# or either a variadic function call or a unary function call. These latter two will be
# defined to be recursive.
#
# Note that the order of the operators in the second argument (the list) of infix_notation matters!
# The operation with the highest precedence is listed first.
infix_expn = infix_notation(
operands | variadic_call | unary_call,
[
(expop, 2, OpAssoc.LEFT),
(signop, 1, OpAssoc.RIGHT),
(multop, 2, OpAssoc.LEFT),
(plusop, 2, OpAssoc.LEFT),
],
)
# These are recursive definitions of the forward declarations of the two type of function calls.
# In essence, the recursion continues until a singleton operand is encountered.
variadic_call <<= Group(
variadic_func_names + lparen + Group(DelimitedList(infix_expn)) + rparen
)
unary_call <<= Group(unary_func_names + lparen + Group(infix_expn) + rparen)
self.expn = infix_expn
def parse(self, str_expr: str) -> ParseResults:
"""Parse a string expression into a list."""
return self.expn.parse_string(str_expr, parse_all=True)
if __name__ == "__main__":
infix_parser = InfixExpressionParser()
expressions = [
"f_1 + f_2 - 1e-3",
"(x_1 + (x_2 * (c_1 + 3.3) / (x_3 - 2))) * 1.5",
"Max(Ln(x) + Lb(Abs(y)), Ceil(Sqrt(garlic) * 3), (potato ** 2) / 4, Abs(cosmic) + 10)",
"Max(Sqrt(Abs(x) + y ** 2), Lg(Max(cosmic, potato)), Ceil(Tanh(x) + Arctan(garlic)))",
"((garlic**3 - 2**Lb(cosmic)) + Ln(x**2 + 1)) / (Sqrt(Square(y) + LogOnePlus(potato + 3.1)))",
]
infix_parser.expn.run_tests(expressions)
|
InfixExpressionParser
|
python
|
rapidsai__cudf
|
python/cudf_polars/cudf_polars/dsl/nodebase.py
|
{
"start": 464,
"end": 4777
}
|
class ____(Generic[T]):
"""
An abstract node type.
Nodes are immutable!
This contains a (potentially empty) tuple of child nodes,
along with non-child data. For uniform reconstruction and
implementation of hashing and equality schemes, child classes need
to provide a certain amount of metadata when they are defined.
Specifically, the ``_non_child`` attribute must list, in-order,
the names of the slots that are passed to the constructor. The
constructor must take arguments in the order ``(*_non_child,
*children).``
"""
__slots__ = ("_hash_value", "_repr_value", "children")
_hash_value: int
_repr_value: str
children: tuple[T, ...]
_non_child: ClassVar[tuple[str, ...]] = ()
def _ctor_arguments(self, children: Sequence[T]) -> Sequence[Any | T]:
return (*(getattr(self, attr) for attr in self._non_child), *children)
def reconstruct(self, children: Sequence[T]) -> Self:
"""
Rebuild this node with new children.
Parameters
----------
children
New children
Returns
-------
New node with new children. Non-child data is shared with the input.
"""
return type(self)(*self._ctor_arguments(children))
def __reduce__(self) -> tuple[Any, ...]:
"""Pickle a Node object."""
return (
type(self),
self._ctor_arguments(self.children),
)
def get_hashable(self) -> Hashable:
"""
Return a hashable object for the node.
Returns
-------
Hashable object.
Notes
-----
This method is used by the :meth:`__hash__` implementation
(which does caching). If your node type needs special-case
handling for some of its attributes, override this method, not
:meth:`__hash__`.
"""
return (type(self), self._ctor_arguments(self.children))
def __hash__(self) -> int:
"""
Hash of an expression with caching.
See Also
--------
get_hashable
"""
try:
return self._hash_value
except AttributeError:
self._hash_value = hash(self.get_hashable())
return self._hash_value
def is_equal(self, other: Self) -> bool:
"""
Equality of two nodes of equal type.
Override this in subclasses, rather than :meth:`__eq__`.
Parameters
----------
other
object of same type to compare to.
Notes
-----
Since nodes are immutable, this does common subexpression
elimination when two nodes are determined to be equal.
:meth:`__eq__` handles the case where the objects being
compared are not of the same type, so in this method, we only
need to implement equality of equal types.
Returns
-------
True if the two nodes are equal, false otherwise.
"""
if self is other:
return True
result = self._ctor_arguments(self.children) == other._ctor_arguments(
other.children
)
# Eager CSE for nodes that match.
if result:
self.children = other.children
return result
def __eq__(self, other: Any) -> bool:
"""
Equality of expressions.
See Also
--------
is_equal
"""
if type(self) is not type(other) or hash(self) != hash(other):
return False
else:
return self.is_equal(other)
def __ne__(self, other: Any) -> bool:
"""Inequality of expressions."""
return not self.__eq__(other)
def __repr__(self) -> str:
"""String representation of an expression with caching."""
try:
return self._repr_value
except AttributeError:
args = ", ".join(f"{arg!r}" for arg in self._ctor_arguments(self.children))
self._repr_value = f"{type(self).__name__}({args})"
return self._repr_value
def __rich_repr__(self) -> Generator[Any, None, None]:
"""Formatting for rich.pretty.pprint."""
for attr in self._non_child:
yield attr, getattr(self, attr)
yield from self.children
|
Node
|
python
|
pypa__setuptools
|
setuptools/_vendor/backports/tarfile/__init__.py
|
{
"start": 58240,
"end": 108491
}
|
class ____(object):
"""The TarFile Class provides an interface to tar archives.
"""
debug = 0 # May be set from 0 (no msgs) to 3 (all msgs)
dereference = False # If true, add content of linked file to the
# tar file, else the link.
ignore_zeros = False # If true, skips empty or invalid blocks and
# continues processing.
errorlevel = 1 # If 0, fatal errors only appear in debug
# messages (if debug >= 0). If > 0, errors
# are passed to the caller as exceptions.
format = DEFAULT_FORMAT # The format to use when creating an archive.
encoding = ENCODING # Encoding for 8-bit character strings.
errors = None # Error handler for unicode conversion.
tarinfo = TarInfo # The default TarInfo class to use.
fileobject = ExFileObject # The file-object for extractfile().
extraction_filter = None # The default filter for extraction.
def __init__(self, name=None, mode="r", fileobj=None, format=None,
tarinfo=None, dereference=None, ignore_zeros=None, encoding=None,
errors="surrogateescape", pax_headers=None, debug=None,
errorlevel=None, copybufsize=None, stream=False):
"""Open an (uncompressed) tar archive 'name'. 'mode' is either 'r' to
read from an existing archive, 'a' to append data to an existing
file or 'w' to create a new file overwriting an existing one. 'mode'
defaults to 'r'.
If 'fileobj' is given, it is used for reading or writing data. If it
can be determined, 'mode' is overridden by 'fileobj's mode.
'fileobj' is not closed, when TarFile is closed.
"""
modes = {"r": "rb", "a": "r+b", "w": "wb", "x": "xb"}
if mode not in modes:
raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
self.mode = mode
self._mode = modes[mode]
if not fileobj:
if self.mode == "a" and not os.path.exists(name):
# Create nonexistent files in append mode.
self.mode = "w"
self._mode = "wb"
fileobj = bltn_open(name, self._mode)
self._extfileobj = False
else:
if (name is None and hasattr(fileobj, "name") and
isinstance(fileobj.name, (str, bytes))):
name = fileobj.name
if hasattr(fileobj, "mode"):
self._mode = fileobj.mode
self._extfileobj = True
self.name = os.path.abspath(name) if name else None
self.fileobj = fileobj
self.stream = stream
# Init attributes.
if format is not None:
self.format = format
if tarinfo is not None:
self.tarinfo = tarinfo
if dereference is not None:
self.dereference = dereference
if ignore_zeros is not None:
self.ignore_zeros = ignore_zeros
if encoding is not None:
self.encoding = encoding
self.errors = errors
if pax_headers is not None and self.format == PAX_FORMAT:
self.pax_headers = pax_headers
else:
self.pax_headers = {}
if debug is not None:
self.debug = debug
if errorlevel is not None:
self.errorlevel = errorlevel
# Init datastructures.
self.copybufsize = copybufsize
self.closed = False
self.members = [] # list of members as TarInfo objects
self._loaded = False # flag if all members have been read
self.offset = self.fileobj.tell()
# current position in the archive file
self.inodes = {} # dictionary caching the inodes of
# archive members already added
try:
if self.mode == "r":
self.firstmember = None
self.firstmember = self.next()
if self.mode == "a":
# Move to the end of the archive,
# before the first empty block.
while True:
self.fileobj.seek(self.offset)
try:
tarinfo = self.tarinfo.fromtarfile(self)
self.members.append(tarinfo)
except EOFHeaderError:
self.fileobj.seek(self.offset)
break
except HeaderError as e:
raise ReadError(str(e)) from None
if self.mode in ("a", "w", "x"):
self._loaded = True
if self.pax_headers:
buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy())
self.fileobj.write(buf)
self.offset += len(buf)
except:
if not self._extfileobj:
self.fileobj.close()
self.closed = True
raise
#--------------------------------------------------------------------------
# Below are the classmethods which act as alternate constructors to the
# TarFile class. The open() method is the only one that is needed for
# public use; it is the "super"-constructor and is able to select an
# adequate "sub"-constructor for a particular compression using the mapping
# from OPEN_METH.
#
# This concept allows one to subclass TarFile without losing the comfort of
# the super-constructor. A sub-constructor is registered and made available
# by adding it to the mapping in OPEN_METH.
@classmethod
def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs):
r"""Open a tar archive for reading, writing or appending. Return
an appropriate TarFile class.
mode:
'r' or 'r:\*' open for reading with transparent compression
'r:' open for reading exclusively uncompressed
'r:gz' open for reading with gzip compression
'r:bz2' open for reading with bzip2 compression
'r:xz' open for reading with lzma compression
'a' or 'a:' open for appending, creating the file if necessary
'w' or 'w:' open for writing without compression
'w:gz' open for writing with gzip compression
'w:bz2' open for writing with bzip2 compression
'w:xz' open for writing with lzma compression
'x' or 'x:' create a tarfile exclusively without compression, raise
an exception if the file is already created
'x:gz' create a gzip compressed tarfile, raise an exception
if the file is already created
'x:bz2' create a bzip2 compressed tarfile, raise an exception
if the file is already created
'x:xz' create an lzma compressed tarfile, raise an exception
if the file is already created
'r|\*' open a stream of tar blocks with transparent compression
'r|' open an uncompressed stream of tar blocks for reading
'r|gz' open a gzip compressed stream of tar blocks
'r|bz2' open a bzip2 compressed stream of tar blocks
'r|xz' open an lzma compressed stream of tar blocks
'w|' open an uncompressed stream for writing
'w|gz' open a gzip compressed stream for writing
'w|bz2' open a bzip2 compressed stream for writing
'w|xz' open an lzma compressed stream for writing
"""
if not name and not fileobj:
raise ValueError("nothing to open")
if mode in ("r", "r:*"):
# Find out which *open() is appropriate for opening the file.
def not_compressed(comptype):
return cls.OPEN_METH[comptype] == 'taropen'
error_msgs = []
for comptype in sorted(cls.OPEN_METH, key=not_compressed):
func = getattr(cls, cls.OPEN_METH[comptype])
if fileobj is not None:
saved_pos = fileobj.tell()
try:
return func(name, "r", fileobj, **kwargs)
except (ReadError, CompressionError) as e:
error_msgs.append(f'- method {comptype}: {e!r}')
if fileobj is not None:
fileobj.seek(saved_pos)
continue
error_msgs_summary = '\n'.join(error_msgs)
raise ReadError(f"file could not be opened successfully:\n{error_msgs_summary}")
elif ":" in mode:
filemode, comptype = mode.split(":", 1)
filemode = filemode or "r"
comptype = comptype or "tar"
# Select the *open() function according to
# given compression.
if comptype in cls.OPEN_METH:
func = getattr(cls, cls.OPEN_METH[comptype])
else:
raise CompressionError("unknown compression type %r" % comptype)
return func(name, filemode, fileobj, **kwargs)
elif "|" in mode:
filemode, comptype = mode.split("|", 1)
filemode = filemode or "r"
comptype = comptype or "tar"
if filemode not in ("r", "w"):
raise ValueError("mode must be 'r' or 'w'")
compresslevel = kwargs.pop("compresslevel", 9)
stream = _Stream(name, filemode, comptype, fileobj, bufsize,
compresslevel)
try:
t = cls(name, filemode, stream, **kwargs)
except:
stream.close()
raise
t._extfileobj = False
return t
elif mode in ("a", "w", "x"):
return cls.taropen(name, mode, fileobj, **kwargs)
raise ValueError("undiscernible mode")
@classmethod
def taropen(cls, name, mode="r", fileobj=None, **kwargs):
"""Open uncompressed tar archive name for reading or writing.
"""
if mode not in ("r", "a", "w", "x"):
raise ValueError("mode must be 'r', 'a', 'w' or 'x'")
return cls(name, mode, fileobj, **kwargs)
@classmethod
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
"""Open gzip compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if mode not in ("r", "w", "x"):
raise ValueError("mode must be 'r', 'w' or 'x'")
try:
from gzip import GzipFile
except ImportError:
raise CompressionError("gzip module is not available") from None
try:
fileobj = GzipFile(name, mode + "b", compresslevel, fileobj)
except OSError as e:
if fileobj is not None and mode == 'r':
raise ReadError("not a gzip file") from e
raise
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except OSError as e:
fileobj.close()
if mode == 'r':
raise ReadError("not a gzip file") from e
raise
except:
fileobj.close()
raise
t._extfileobj = False
return t
@classmethod
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
"""Open bzip2 compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if mode not in ("r", "w", "x"):
raise ValueError("mode must be 'r', 'w' or 'x'")
try:
from bz2 import BZ2File
except ImportError:
raise CompressionError("bz2 module is not available") from None
fileobj = BZ2File(fileobj or name, mode, compresslevel=compresslevel)
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except (OSError, EOFError) as e:
fileobj.close()
if mode == 'r':
raise ReadError("not a bzip2 file") from e
raise
except:
fileobj.close()
raise
t._extfileobj = False
return t
@classmethod
def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
"""Open lzma compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if mode not in ("r", "w", "x"):
raise ValueError("mode must be 'r', 'w' or 'x'")
try:
from lzma import LZMAFile, LZMAError
except ImportError:
raise CompressionError("lzma module is not available") from None
fileobj = LZMAFile(fileobj or name, mode, preset=preset)
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except (LZMAError, EOFError) as e:
fileobj.close()
if mode == 'r':
raise ReadError("not an lzma file") from e
raise
except:
fileobj.close()
raise
t._extfileobj = False
return t
# All *open() methods are registered here.
OPEN_METH = {
"tar": "taropen", # uncompressed tar
"gz": "gzopen", # gzip compressed tar
"bz2": "bz2open", # bzip2 compressed tar
"xz": "xzopen" # lzma compressed tar
}
#--------------------------------------------------------------------------
# The public methods which TarFile provides:
def close(self):
"""Close the TarFile. In write-mode, two finishing zero blocks are
appended to the archive.
"""
if self.closed:
return
self.closed = True
try:
if self.mode in ("a", "w", "x"):
self.fileobj.write(NUL * (BLOCKSIZE * 2))
self.offset += (BLOCKSIZE * 2)
# fill up the end with zero-blocks
# (like option -b20 for tar does)
blocks, remainder = divmod(self.offset, RECORDSIZE)
if remainder > 0:
self.fileobj.write(NUL * (RECORDSIZE - remainder))
finally:
if not self._extfileobj:
self.fileobj.close()
def getmember(self, name):
"""Return a TarInfo object for member 'name'. If 'name' can not be
found in the archive, KeyError is raised. If a member occurs more
than once in the archive, its last occurrence is assumed to be the
most up-to-date version.
"""
tarinfo = self._getmember(name.rstrip('/'))
if tarinfo is None:
raise KeyError("filename %r not found" % name)
return tarinfo
def getmembers(self):
"""Return the members of the archive as a list of TarInfo objects. The
list has the same order as the members in the archive.
"""
self._check()
if not self._loaded: # if we want to obtain a list of
self._load() # all members, we first have to
# scan the whole archive.
return self.members
def getnames(self):
"""Return the members of the archive as a list of their names. It has
the same order as the list returned by getmembers().
"""
return [tarinfo.name for tarinfo in self.getmembers()]
def gettarinfo(self, name=None, arcname=None, fileobj=None):
"""Create a TarInfo object from the result of os.stat or equivalent
on an existing file. The file is either named by 'name', or
specified as a file object 'fileobj' with a file descriptor. If
given, 'arcname' specifies an alternative name for the file in the
archive, otherwise, the name is taken from the 'name' attribute of
'fileobj', or the 'name' argument. The name should be a text
string.
"""
self._check("awx")
# When fileobj is given, replace name by
# fileobj's real name.
if fileobj is not None:
name = fileobj.name
# Building the name of the member in the archive.
# Backward slashes are converted to forward slashes,
# Absolute paths are turned to relative paths.
if arcname is None:
arcname = name
drv, arcname = os.path.splitdrive(arcname)
arcname = arcname.replace(os.sep, "/")
arcname = arcname.lstrip("/")
# Now, fill the TarInfo object with
# information specific for the file.
tarinfo = self.tarinfo()
tarinfo._tarfile = self # To be removed in 3.16.
# Use os.stat or os.lstat, depending on if symlinks shall be resolved.
if fileobj is None:
if not self.dereference:
statres = os.lstat(name)
else:
statres = os.stat(name)
else:
statres = os.fstat(fileobj.fileno())
linkname = ""
stmd = statres.st_mode
if stat.S_ISREG(stmd):
inode = (statres.st_ino, statres.st_dev)
if not self.dereference and statres.st_nlink > 1 and \
inode in self.inodes and arcname != self.inodes[inode]:
# Is it a hardlink to an already
# archived file?
type = LNKTYPE
linkname = self.inodes[inode]
else:
# The inode is added only if its valid.
# For win32 it is always 0.
type = REGTYPE
if inode[0]:
self.inodes[inode] = arcname
elif stat.S_ISDIR(stmd):
type = DIRTYPE
elif stat.S_ISFIFO(stmd):
type = FIFOTYPE
elif stat.S_ISLNK(stmd):
type = SYMTYPE
linkname = os.readlink(name)
elif stat.S_ISCHR(stmd):
type = CHRTYPE
elif stat.S_ISBLK(stmd):
type = BLKTYPE
else:
return None
# Fill the TarInfo object with all
# information we can get.
tarinfo.name = arcname
tarinfo.mode = stmd
tarinfo.uid = statres.st_uid
tarinfo.gid = statres.st_gid
if type == REGTYPE:
tarinfo.size = statres.st_size
else:
tarinfo.size = 0
tarinfo.mtime = statres.st_mtime
tarinfo.type = type
tarinfo.linkname = linkname
if pwd:
try:
tarinfo.uname = pwd.getpwuid(tarinfo.uid)[0]
except KeyError:
pass
if grp:
try:
tarinfo.gname = grp.getgrgid(tarinfo.gid)[0]
except KeyError:
pass
if type in (CHRTYPE, BLKTYPE):
if hasattr(os, "major") and hasattr(os, "minor"):
tarinfo.devmajor = os.major(statres.st_rdev)
tarinfo.devminor = os.minor(statres.st_rdev)
return tarinfo
def list(self, verbose=True, *, members=None):
"""Print a table of contents to sys.stdout. If 'verbose' is False, only
the names of the members are printed. If it is True, an 'ls -l'-like
output is produced. 'members' is optional and must be a subset of the
list returned by getmembers().
"""
# Convert tarinfo type to stat type.
type2mode = {REGTYPE: stat.S_IFREG, SYMTYPE: stat.S_IFLNK,
FIFOTYPE: stat.S_IFIFO, CHRTYPE: stat.S_IFCHR,
DIRTYPE: stat.S_IFDIR, BLKTYPE: stat.S_IFBLK}
self._check()
if members is None:
members = self
for tarinfo in members:
if verbose:
if tarinfo.mode is None:
_safe_print("??????????")
else:
modetype = type2mode.get(tarinfo.type, 0)
_safe_print(stat.filemode(modetype | tarinfo.mode))
_safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
tarinfo.gname or tarinfo.gid))
if tarinfo.ischr() or tarinfo.isblk():
_safe_print("%10s" %
("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
else:
_safe_print("%10d" % tarinfo.size)
if tarinfo.mtime is None:
_safe_print("????-??-?? ??:??:??")
else:
_safe_print("%d-%02d-%02d %02d:%02d:%02d" \
% time.localtime(tarinfo.mtime)[:6])
_safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
if verbose:
if tarinfo.issym():
_safe_print("-> " + tarinfo.linkname)
if tarinfo.islnk():
_safe_print("link to " + tarinfo.linkname)
print()
def add(self, name, arcname=None, recursive=True, *, filter=None):
"""Add the file 'name' to the archive. 'name' may be any type of file
(directory, fifo, symbolic link, etc.). If given, 'arcname'
specifies an alternative name for the file in the archive.
Directories are added recursively by default. This can be avoided by
setting 'recursive' to False. 'filter' is a function
that expects a TarInfo object argument and returns the changed
TarInfo object, if it returns None the TarInfo object will be
excluded from the archive.
"""
self._check("awx")
if arcname is None:
arcname = name
# Skip if somebody tries to archive the archive...
if self.name is not None and os.path.abspath(name) == self.name:
self._dbg(2, "tarfile: Skipped %r" % name)
return
self._dbg(1, name)
# Create a TarInfo object from the file.
tarinfo = self.gettarinfo(name, arcname)
if tarinfo is None:
self._dbg(1, "tarfile: Unsupported type %r" % name)
return
# Change or exclude the TarInfo object.
if filter is not None:
tarinfo = filter(tarinfo)
if tarinfo is None:
self._dbg(2, "tarfile: Excluded %r" % name)
return
# Append the tar header and data to the archive.
if tarinfo.isreg():
with bltn_open(name, "rb") as f:
self.addfile(tarinfo, f)
elif tarinfo.isdir():
self.addfile(tarinfo)
if recursive:
for f in sorted(os.listdir(name)):
self.add(os.path.join(name, f), os.path.join(arcname, f),
recursive, filter=filter)
else:
self.addfile(tarinfo)
def addfile(self, tarinfo, fileobj=None):
"""Add the TarInfo object 'tarinfo' to the archive. If 'tarinfo' represents
a non zero-size regular file, the 'fileobj' argument should be a binary file,
and tarinfo.size bytes are read from it and added to the archive.
You can create TarInfo objects directly, or by using gettarinfo().
"""
self._check("awx")
if fileobj is None and tarinfo.isreg() and tarinfo.size != 0:
raise ValueError("fileobj not provided for non zero-size regular file")
tarinfo = copy.copy(tarinfo)
buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
self.fileobj.write(buf)
self.offset += len(buf)
bufsize=self.copybufsize
# If there's data to follow, append it.
if fileobj is not None:
copyfileobj(fileobj, self.fileobj, tarinfo.size, bufsize=bufsize)
blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
if remainder > 0:
self.fileobj.write(NUL * (BLOCKSIZE - remainder))
blocks += 1
self.offset += blocks * BLOCKSIZE
self.members.append(tarinfo)
def _get_filter_function(self, filter):
if filter is None:
filter = self.extraction_filter
if filter is None:
import warnings
warnings.warn(
'Python 3.14 will, by default, filter extracted tar '
+ 'archives and reject files or modify their metadata. '
+ 'Use the filter argument to control this behavior.',
DeprecationWarning, stacklevel=3)
return fully_trusted_filter
if isinstance(filter, str):
raise TypeError(
'String names are not supported for '
+ 'TarFile.extraction_filter. Use a function such as '
+ 'tarfile.data_filter directly.')
return filter
if callable(filter):
return filter
try:
return _NAMED_FILTERS[filter]
except KeyError:
raise ValueError(f"filter {filter!r} not found") from None
def extractall(self, path=".", members=None, *, numeric_owner=False,
filter=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. 'path' specifies a different directory
to extract to. 'members' is optional and must be a subset of the
list returned by getmembers(). If 'numeric_owner' is True, only
the numbers for user/group names are used and not the names.
The 'filter' function will be called on each member just
before extraction.
It can return a changed TarInfo or None to skip the member.
String names of common filters are accepted.
"""
directories = []
filter_function = self._get_filter_function(filter)
if members is None:
members = self
for member in members:
tarinfo = self._get_extract_tarinfo(member, filter_function, path)
if tarinfo is None:
continue
if tarinfo.isdir():
# For directories, delay setting attributes until later,
# since permissions can interfere with extraction and
# extracting contents can reset mtime.
directories.append(tarinfo)
self._extract_one(tarinfo, path, set_attrs=not tarinfo.isdir(),
numeric_owner=numeric_owner)
# Reverse sort directories.
directories.sort(key=lambda a: a.name, reverse=True)
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath, numeric_owner=numeric_owner)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError as e:
self._handle_nonfatal_error(e)
def extract(self, member, path="", set_attrs=True, *, numeric_owner=False,
filter=None):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. 'member' may be a filename or a TarInfo object. You can
specify a different directory using 'path'. File attributes (owner,
mtime, mode) are set unless 'set_attrs' is False. If 'numeric_owner'
is True, only the numbers for user/group names are used and not
the names.
The 'filter' function will be called before extraction.
It can return a changed TarInfo or None to skip the member.
String names of common filters are accepted.
"""
filter_function = self._get_filter_function(filter)
tarinfo = self._get_extract_tarinfo(member, filter_function, path)
if tarinfo is not None:
self._extract_one(tarinfo, path, set_attrs, numeric_owner)
def _get_extract_tarinfo(self, member, filter_function, path):
"""Get filtered TarInfo (or None) from member, which might be a str"""
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
unfiltered = tarinfo
try:
tarinfo = filter_function(tarinfo, path)
except (OSError, FilterError) as e:
self._handle_fatal_error(e)
except ExtractError as e:
self._handle_nonfatal_error(e)
if tarinfo is None:
self._dbg(2, "tarfile: Excluded %r" % unfiltered.name)
return None
# Prepare the link target for makelink().
if tarinfo.islnk():
tarinfo = copy.copy(tarinfo)
tarinfo._link_target = os.path.join(path, tarinfo.linkname)
return tarinfo
def _extract_one(self, tarinfo, path, set_attrs, numeric_owner):
"""Extract from filtered tarinfo to disk"""
self._check("r")
try:
self._extract_member(tarinfo, os.path.join(path, tarinfo.name),
set_attrs=set_attrs,
numeric_owner=numeric_owner)
except OSError as e:
self._handle_fatal_error(e)
except ExtractError as e:
self._handle_nonfatal_error(e)
def _handle_nonfatal_error(self, e):
"""Handle non-fatal error (ExtractError) according to errorlevel"""
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
def _handle_fatal_error(self, e):
"""Handle "fatal" error according to self.errorlevel"""
if self.errorlevel > 0:
raise
elif isinstance(e, OSError):
if e.filename is None:
self._dbg(1, "tarfile: %s" % e.strerror)
else:
self._dbg(1, "tarfile: %s %r" % (e.strerror, e.filename))
else:
self._dbg(1, "tarfile: %s %s" % (type(e).__name__, e))
def extractfile(self, member):
"""Extract a member from the archive as a file object. 'member' may be
a filename or a TarInfo object. If 'member' is a regular file or
a link, an io.BufferedReader object is returned. For all other
existing members, None is returned. If 'member' does not appear
in the archive, KeyError is raised.
"""
self._check("r")
if isinstance(member, str):
tarinfo = self.getmember(member)
else:
tarinfo = member
if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES:
# Members with unknown types are treated as regular files.
return self.fileobject(self, tarinfo)
elif tarinfo.islnk() or tarinfo.issym():
if isinstance(self.fileobj, _Stream):
# A small but ugly workaround for the case that someone tries
# to extract a (sym)link as a file-object from a non-seekable
# stream of tar blocks.
raise StreamError("cannot extract (sym)link as file object")
else:
# A (sym)link's file object is its target's file object.
return self.extractfile(self._find_link_target(tarinfo))
else:
# If there's no data associated with the member (directory, chrdev,
# blkdev, etc.), return None instead of a file object.
return None
def _extract_member(self, tarinfo, targetpath, set_attrs=True,
numeric_owner=False):
"""Extract the TarInfo object tarinfo to a physical
file called targetpath.
"""
# Fetch the TarInfo object for the given name
# and build the destination pathname, replacing
# forward slashes to platform specific separators.
targetpath = targetpath.rstrip("/")
targetpath = targetpath.replace("/", os.sep)
# Create all upper directories.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
# Create directories that are not part of the archive with
# default permissions.
os.makedirs(upperdirs, exist_ok=True)
if tarinfo.islnk() or tarinfo.issym():
self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
else:
self._dbg(1, tarinfo.name)
if tarinfo.isreg():
self.makefile(tarinfo, targetpath)
elif tarinfo.isdir():
self.makedir(tarinfo, targetpath)
elif tarinfo.isfifo():
self.makefifo(tarinfo, targetpath)
elif tarinfo.ischr() or tarinfo.isblk():
self.makedev(tarinfo, targetpath)
elif tarinfo.islnk() or tarinfo.issym():
self.makelink(tarinfo, targetpath)
elif tarinfo.type not in SUPPORTED_TYPES:
self.makeunknown(tarinfo, targetpath)
else:
self.makefile(tarinfo, targetpath)
if set_attrs:
self.chown(tarinfo, targetpath, numeric_owner)
if not tarinfo.issym():
self.chmod(tarinfo, targetpath)
self.utime(tarinfo, targetpath)
#--------------------------------------------------------------------------
# Below are the different file methods. They are called via
# _extract_member() when extract() is called. They can be replaced in a
# subclass to implement other functionality.
def makedir(self, tarinfo, targetpath):
"""Make a directory called targetpath.
"""
try:
if tarinfo.mode is None:
# Use the system's default mode
os.mkdir(targetpath)
else:
# Use a safe mode for the directory, the real mode is set
# later in _extract_member().
os.mkdir(targetpath, 0o700)
except FileExistsError:
if not os.path.isdir(targetpath):
raise
def makefile(self, tarinfo, targetpath):
"""Make a file called targetpath.
"""
source = self.fileobj
source.seek(tarinfo.offset_data)
bufsize = self.copybufsize
with bltn_open(targetpath, "wb") as target:
if tarinfo.sparse is not None:
for offset, size in tarinfo.sparse:
target.seek(offset)
copyfileobj(source, target, size, ReadError, bufsize)
target.seek(tarinfo.size)
target.truncate()
else:
copyfileobj(source, target, tarinfo.size, ReadError, bufsize)
def makeunknown(self, tarinfo, targetpath):
"""Make a file from a TarInfo object with an unknown type
at targetpath.
"""
self.makefile(tarinfo, targetpath)
self._dbg(1, "tarfile: Unknown file type %r, " \
"extracted as regular file." % tarinfo.type)
def makefifo(self, tarinfo, targetpath):
"""Make a fifo called targetpath.
"""
if hasattr(os, "mkfifo"):
os.mkfifo(targetpath)
else:
raise ExtractError("fifo not supported by system")
def makedev(self, tarinfo, targetpath):
"""Make a character or block device called targetpath.
"""
if not hasattr(os, "mknod") or not hasattr(os, "makedev"):
raise ExtractError("special devices not supported by system")
mode = tarinfo.mode
if mode is None:
# Use mknod's default
mode = 0o600
if tarinfo.isblk():
mode |= stat.S_IFBLK
else:
mode |= stat.S_IFCHR
os.mknod(targetpath, mode,
os.makedev(tarinfo.devmajor, tarinfo.devminor))
def makelink(self, tarinfo, targetpath):
"""Make a (symbolic) link called targetpath. If it cannot be created
(platform limitation), we try to make a copy of the referenced file
instead of a link.
"""
try:
# For systems that support symbolic and hard links.
if tarinfo.issym():
if os.path.lexists(targetpath):
# Avoid FileExistsError on following os.symlink.
os.unlink(targetpath)
os.symlink(tarinfo.linkname, targetpath)
else:
if os.path.exists(tarinfo._link_target):
os.link(tarinfo._link_target, targetpath)
else:
self._extract_member(self._find_link_target(tarinfo),
targetpath)
except symlink_exception:
try:
self._extract_member(self._find_link_target(tarinfo),
targetpath)
except KeyError:
raise ExtractError("unable to resolve link inside archive") from None
def chown(self, tarinfo, targetpath, numeric_owner):
"""Set owner of targetpath according to tarinfo. If numeric_owner
is True, use .gid/.uid instead of .gname/.uname. If numeric_owner
is False, fall back to .gid/.uid when the search based on name
fails.
"""
if hasattr(os, "geteuid") and os.geteuid() == 0:
# We have to be root to do so.
g = tarinfo.gid
u = tarinfo.uid
if not numeric_owner:
try:
if grp and tarinfo.gname:
g = grp.getgrnam(tarinfo.gname)[2]
except KeyError:
pass
try:
if pwd and tarinfo.uname:
u = pwd.getpwnam(tarinfo.uname)[2]
except KeyError:
pass
if g is None:
g = -1
if u is None:
u = -1
try:
if tarinfo.issym() and hasattr(os, "lchown"):
os.lchown(targetpath, u, g)
else:
os.chown(targetpath, u, g)
except (OSError, OverflowError) as e:
# OverflowError can be raised if an ID doesn't fit in 'id_t'
raise ExtractError("could not change owner") from e
def chmod(self, tarinfo, targetpath):
"""Set file permissions of targetpath according to tarinfo.
"""
if tarinfo.mode is None:
return
try:
os.chmod(targetpath, tarinfo.mode)
except OSError as e:
raise ExtractError("could not change mode") from e
def utime(self, tarinfo, targetpath):
"""Set modification time of targetpath according to tarinfo.
"""
mtime = tarinfo.mtime
if mtime is None:
return
if not hasattr(os, 'utime'):
return
try:
os.utime(targetpath, (mtime, mtime))
except OSError as e:
raise ExtractError("could not change modification time") from e
#--------------------------------------------------------------------------
def next(self):
"""Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
"""
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firstmember = None
return m
# Advance the file pointer.
if self.offset != self.fileobj.tell():
if self.offset == 0:
return None
self.fileobj.seek(self.offset - 1)
if not self.fileobj.read(1):
raise ReadError("unexpected end of data")
# Read the next block.
tarinfo = None
while True:
try:
tarinfo = self.tarinfo.fromtarfile(self)
except EOFHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
except InvalidHeaderError as e:
if self.ignore_zeros:
self._dbg(2, "0x%X: %s" % (self.offset, e))
self.offset += BLOCKSIZE
continue
elif self.offset == 0:
raise ReadError(str(e)) from None
except EmptyHeaderError:
if self.offset == 0:
raise ReadError("empty file") from None
except TruncatedHeaderError as e:
if self.offset == 0:
raise ReadError(str(e)) from None
except SubsequentHeaderError as e:
raise ReadError(str(e)) from None
except Exception as e:
try:
import zlib
if isinstance(e, zlib.error):
raise ReadError(f'zlib error: {e}') from None
else:
raise e
except ImportError:
raise e
break
if tarinfo is not None:
# if streaming the file we do not want to cache the tarinfo
if not self.stream:
self.members.append(tarinfo)
else:
self._loaded = True
return tarinfo
#--------------------------------------------------------------------------
# Little helper methods:
def _getmember(self, name, tarinfo=None, normalize=False):
"""Find an archive member by name from bottom to top.
If tarinfo is given, it is used as the starting point.
"""
# Ensure that all members have been loaded.
members = self.getmembers()
# Limit the member search list up to tarinfo.
skipping = False
if tarinfo is not None:
try:
index = members.index(tarinfo)
except ValueError:
# The given starting point might be a (modified) copy.
# We'll later skip members until we find an equivalent.
skipping = True
else:
# Happy fast path
members = members[:index]
if normalize:
name = os.path.normpath(name)
for member in reversed(members):
if skipping:
if tarinfo.offset == member.offset:
skipping = False
continue
if normalize:
member_name = os.path.normpath(member.name)
else:
member_name = member.name
if name == member_name:
return member
if skipping:
# Starting point was not found
raise ValueError(tarinfo)
def _load(self):
"""Read through the entire archive file and look for readable
members. This should not run if the file is set to stream.
"""
if not self.stream:
while self.next() is not None:
pass
self._loaded = True
def _check(self, mode=None):
"""Check if TarFile is still open, and if the operation's mode
corresponds to TarFile's mode.
"""
if self.closed:
raise OSError("%s is closed" % self.__class__.__name__)
if mode is not None and self.mode not in mode:
raise OSError("bad operation for mode %r" % self.mode)
def _find_link_target(self, tarinfo):
"""Find the target member of a symlink or hardlink member in the
archive.
"""
if tarinfo.issym():
# Always search the entire archive.
linkname = "/".join(filter(None, (os.path.dirname(tarinfo.name), tarinfo.linkname)))
limit = None
else:
# Search the archive before the link, because a hard link is
# just a reference to an already archived file.
linkname = tarinfo.linkname
limit = tarinfo
member = self._getmember(linkname, tarinfo=limit, normalize=True)
if member is None:
raise KeyError("linkname %r not found" % linkname)
return member
def __iter__(self):
"""Provide an iterator object.
"""
if self._loaded:
yield from self.members
return
# Yield items using TarFile's next() method.
# When all members have been read, set TarFile as _loaded.
index = 0
# Fix for SF #1100429: Under rare circumstances it can
# happen that getmembers() is called during iteration,
# which will have already exhausted the next() method.
if self.firstmember is not None:
tarinfo = self.next()
index += 1
yield tarinfo
while True:
if index < len(self.members):
tarinfo = self.members[index]
elif not self._loaded:
tarinfo = self.next()
if not tarinfo:
self._loaded = True
return
else:
return
index += 1
yield tarinfo
def _dbg(self, level, msg):
"""Write debugging output to sys.stderr.
"""
if level <= self.debug:
print(msg, file=sys.stderr)
def __enter__(self):
self._check()
return self
def __exit__(self, type, value, traceback):
if type is None:
self.close()
else:
# An exception occurred. We must not call close() because
# it would try to write end-of-archive blocks and padding.
if not self._extfileobj:
self.fileobj.close()
self.closed = True
#--------------------
# exported functions
#--------------------
def is_tarfile(name):
"""Return True if name points to a tar archive that we
are able to handle, else return False.
'name' should be a string, file, or file-like object.
"""
try:
if hasattr(name, "read"):
pos = name.tell()
t = open(fileobj=name)
name.seek(pos)
else:
t = open(name)
t.close()
return True
except TarError:
return False
open = TarFile.open
def main():
import argparse
description = 'A simple command-line interface for tarfile module.'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-v', '--verbose', action='store_true', default=False,
help='Verbose output')
parser.add_argument('--filter', metavar='<filtername>',
choices=_NAMED_FILTERS,
help='Filter for extraction')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', metavar='<tarfile>',
help='Show listing of a tarfile')
group.add_argument('-e', '--extract', nargs='+',
metavar=('<tarfile>', '<output_dir>'),
help='Extract tarfile into target dir')
group.add_argument('-c', '--create', nargs='+',
metavar=('<name>', '<file>'),
help='Create tarfile from sources')
group.add_argument('-t', '--test', metavar='<tarfile>',
help='Test if a tarfile is valid')
args = parser.parse_args()
if args.filter and args.extract is None:
parser.exit(1, '--filter is only valid for extraction\n')
if args.test is not None:
src = args.test
if is_tarfile(src):
with open(src, 'r') as tar:
tar.getmembers()
print(tar.getmembers(), file=sys.stderr)
if args.verbose:
print('{!r} is a tar archive.'.format(src))
else:
parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
elif args.list is not None:
src = args.list
if is_tarfile(src):
with TarFile.open(src, 'r:*') as tf:
tf.list(verbose=args.verbose)
else:
parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
elif args.extract is not None:
if len(args.extract) == 1:
src = args.extract[0]
curdir = os.curdir
elif len(args.extract) == 2:
src, curdir = args.extract
else:
parser.exit(1, parser.format_help())
if is_tarfile(src):
with TarFile.open(src, 'r:*') as tf:
tf.extractall(path=curdir, filter=args.filter)
if args.verbose:
if curdir == '.':
msg = '{!r} file is extracted.'.format(src)
else:
msg = ('{!r} file is extracted '
'into {!r} directory.').format(src, curdir)
print(msg)
else:
parser.exit(1, '{!r} is not a tar archive.\n'.format(src))
elif args.create is not None:
tar_name = args.create.pop(0)
_, ext = os.path.splitext(tar_name)
compressions = {
# gz
'.gz': 'gz',
'.tgz': 'gz',
# xz
'.xz': 'xz',
'.txz': 'xz',
# bz2
'.bz2': 'bz2',
'.tbz': 'bz2',
'.tbz2': 'bz2',
'.tb2': 'bz2',
}
tar_mode = 'w:' + compressions[ext] if ext in compressions else 'w'
tar_files = args.create
with TarFile.open(tar_name, tar_mode) as tf:
for file_name in tar_files:
tf.add(file_name)
if args.verbose:
print('{!r} file created.'.format(tar_name))
if __name__ == '__main__':
main()
|
TarFile
|
python
|
simonw__sqlite-utils
|
sqlite_utils/db.py
|
{
"start": 5897,
"end": 5990
}
|
class ____(Exception):
"Could not tell which table this operation refers to"
|
NoObviousTable
|
python
|
pallets__werkzeug
|
src/werkzeug/wsgi.py
|
{
"start": 11762,
"end": 14740
}
|
class ____:
# private for now, but should we make it public in the future ?
"""This class can be used to convert an iterable object into
an iterable that will only yield a piece of the underlying content.
It yields blocks until the underlying stream range is fully read.
The yielded blocks will have a size that can't exceed the original
iterator defined block size, but that can be smaller.
If you're using this object together with a :class:`Response` you have
to use the `direct_passthrough` mode.
:param iterable: an iterable object with a :meth:`__next__` method.
:param start_byte: byte from which read will start.
:param byte_range: how many bytes to read.
"""
def __init__(
self,
iterable: t.Iterable[bytes] | t.IO[bytes],
start_byte: int = 0,
byte_range: int | None = None,
):
self.iterable = iter(iterable)
self.byte_range = byte_range
self.start_byte = start_byte
self.end_byte = None
if byte_range is not None:
self.end_byte = start_byte + byte_range
self.read_length = 0
self.seekable = hasattr(iterable, "seekable") and iterable.seekable()
self.end_reached = False
def __iter__(self) -> _RangeWrapper:
return self
def _next_chunk(self) -> bytes:
try:
chunk = next(self.iterable)
self.read_length += len(chunk)
return chunk
except StopIteration:
self.end_reached = True
raise
def _first_iteration(self) -> tuple[bytes | None, int]:
chunk = None
if self.seekable:
self.iterable.seek(self.start_byte) # type: ignore
self.read_length = self.iterable.tell() # type: ignore
contextual_read_length = self.read_length
else:
while self.read_length <= self.start_byte:
chunk = self._next_chunk()
if chunk is not None:
chunk = chunk[self.start_byte - self.read_length :]
contextual_read_length = self.start_byte
return chunk, contextual_read_length
def _next(self) -> bytes:
if self.end_reached:
raise StopIteration()
chunk = None
contextual_read_length = self.read_length
if self.read_length == 0:
chunk, contextual_read_length = self._first_iteration()
if chunk is None:
chunk = self._next_chunk()
if self.end_byte is not None and self.read_length >= self.end_byte:
self.end_reached = True
return chunk[: self.end_byte - contextual_read_length]
return chunk
def __next__(self) -> bytes:
chunk = self._next()
if chunk:
return chunk
self.end_reached = True
raise StopIteration()
def close(self) -> None:
if hasattr(self.iterable, "close"):
self.iterable.close()
|
_RangeWrapper
|
python
|
pola-rs__polars
|
py-polars/src/polars/expr/string.py
|
{
"start": 1166,
"end": 115235
}
|
class ____:
"""Namespace for string related expressions."""
_accessor = "str"
def __init__(self, expr: Expr) -> None:
self._pyexpr = expr._pyexpr
def to_date(
self,
format: str | None = None,
*,
strict: bool = True,
exact: bool = True,
cache: bool = True,
) -> Expr:
"""
Convert a String column into a Date column.
Parameters
----------
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%Y-%m-%d"`.
If set to None (default), the format is inferred from the data.
strict
Raise an error if any conversion fails.
exact
Require an exact format match. If False, allow the format to match anywhere
in the target string.
.. note::
Using `exact=False` introduces a performance penalty - cleaning your
data beforehand will almost certainly be more performant.
cache
Use a cache of unique, converted dates to apply the conversion.
Examples
--------
>>> s = pl.Series(["2020/01/01", "2020/02/01", "2020/03/01"])
>>> s.str.to_date()
shape: (3,)
Series: '' [date]
[
2020-01-01
2020-02-01
2020-03-01
]
"""
_validate_format_argument(format)
return wrap_expr(self._pyexpr.str_to_date(format, strict, exact, cache))
def to_datetime(
self,
format: str | None = None,
*,
time_unit: TimeUnit | None = None,
time_zone: str | None = None,
strict: bool = True,
exact: bool = True,
cache: bool = True,
ambiguous: Ambiguous | Expr = "raise",
) -> Expr:
"""
Convert a String column into a Datetime column.
Parameters
----------
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%Y-%m-%d %H:%M:%S"`.
If set to None (default), the format is inferred from the data.
time_unit : {None, 'us', 'ns', 'ms'}
Unit of time for the resulting Datetime column. If set to None (default),
the time unit is inferred from the format string if given, eg:
`"%F %T%.3f"` => `Datetime("ms")`. If no fractional second component is
found, the default is `"us"`.
time_zone
Time zone for the resulting Datetime column. Rules are:
- If inputs are tz-naive and `time_zone` is None, the result time zone is
`None`.
- If inputs are offset-aware and `time_zone` is None, inputs are converted
to `'UTC'` and the result time zone is `'UTC'`.
- If inputs are offset-aware and `time_zone` is given, inputs are converted
to `time_zone` and the result time zone is `time_zone`.
- If inputs are tz-naive and `time_zone` is given, input time zones are
replaced with (not converted to!) `time_zone`, and the result time zone
is `time_zone`.
strict
Raise an error if any conversion fails.
exact
Require an exact format match. If False, allow the format to match anywhere
in the target string.
.. note::
Using `exact=False` introduces a performance penalty - cleaning your
data beforehand will almost certainly be more performant.
cache
Use a cache of unique, converted datetimes to apply the conversion.
ambiguous
Determine how to deal with ambiguous datetimes:
- `'raise'` (default): raise
- `'earliest'`: use the earliest datetime
- `'latest'`: use the latest datetime
- `'null'`: set to null
Examples
--------
>>> s = pl.Series(["2020-01-01 01:00Z", "2020-01-01 02:00Z"])
>>> s.str.to_datetime("%Y-%m-%d %H:%M%#z")
shape: (2,)
Series: '' [datetime[μs, UTC]]
[
2020-01-01 01:00:00 UTC
2020-01-01 02:00:00 UTC
]
"""
_validate_format_argument(format)
if not isinstance(ambiguous, pl.Expr):
ambiguous = F.lit(ambiguous)
return wrap_expr(
self._pyexpr.str_to_datetime(
format,
time_unit,
time_zone,
strict,
exact,
cache,
ambiguous._pyexpr,
)
)
def to_time(
self,
format: str | None = None,
*,
strict: bool = True,
cache: bool = True,
) -> Expr:
"""
Convert a String column into a Time column.
Parameters
----------
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%H:%M:%S"`.
If set to None (default), the format is inferred from the data.
strict
Raise an error if any conversion fails.
cache
Use a cache of unique, converted times to apply the conversion.
Examples
--------
>>> s = pl.Series(["01:00", "02:00", "03:00"])
>>> s.str.to_time("%H:%M")
shape: (3,)
Series: '' [time]
[
01:00:00
02:00:00
03:00:00
]
"""
_validate_format_argument(format)
return wrap_expr(self._pyexpr.str_to_time(format, strict, cache))
def strptime(
self,
dtype: PolarsTemporalType,
format: str | None = None,
*,
strict: bool = True,
exact: bool = True,
cache: bool = True,
ambiguous: Ambiguous | Expr = "raise",
) -> Expr:
"""
Convert a String column into a Date/Datetime/Time column.
Parameters
----------
dtype
The data type to convert into. Can be either Date, Datetime, or Time.
format
Format to use for conversion. Refer to the `chrono crate documentation
<https://docs.rs/chrono/latest/chrono/format/strftime/index.html>`_
for the full specification. Example: `"%Y-%m-%d %H:%M:%S"`.
If set to None (default), the format is inferred from the data.
strict
Raise an error if any conversion fails.
exact
Require an exact format match. If False, allow the format to match anywhere
in the target string. Conversion to the Time type is always exact.
.. note::
Using `exact=False` introduces a performance penalty - cleaning your
data beforehand will almost certainly be more performant.
cache
Use a cache of unique, converted dates to apply the datetime conversion.
ambiguous
Determine how to deal with ambiguous datetimes:
- `'raise'` (default): raise
- `'earliest'`: use the earliest datetime
- `'latest'`: use the latest datetime
- `'null'`: set to null
Notes
-----
When converting to a Datetime type, the time unit is inferred from the format
string if given, eg: `"%F %T%.3f"` => `Datetime("ms")`. If no fractional
second component is found, the default is `"us"`.
Examples
--------
Dealing with a consistent format:
>>> s = pl.Series(["2020-01-01 01:00Z", "2020-01-01 02:00Z"])
>>> s.str.strptime(pl.Datetime, "%Y-%m-%d %H:%M%#z")
shape: (2,)
Series: '' [datetime[μs, UTC]]
[
2020-01-01 01:00:00 UTC
2020-01-01 02:00:00 UTC
]
Dealing with different formats.
>>> s = pl.Series(
... "date",
... [
... "2021-04-22",
... "2022-01-04 00:00:00",
... "01/31/22",
... "Sun Jul 8 00:34:60 2001",
... ],
... )
>>> s.to_frame().select(
... pl.coalesce(
... pl.col("date").str.strptime(pl.Date, "%F", strict=False),
... pl.col("date").str.strptime(pl.Date, "%F %T", strict=False),
... pl.col("date").str.strptime(pl.Date, "%D", strict=False),
... pl.col("date").str.strptime(pl.Date, "%c", strict=False),
... )
... ).to_series()
shape: (4,)
Series: 'date' [date]
[
2021-04-22
2022-01-04
2022-01-31
2001-07-08
]
"""
if dtype == Date:
return self.to_date(format, strict=strict, exact=exact, cache=cache)
elif dtype == Datetime:
time_unit = getattr(dtype, "time_unit", None)
time_zone = getattr(dtype, "time_zone", None)
return self.to_datetime(
format,
time_unit=time_unit,
time_zone=time_zone,
strict=strict,
exact=exact,
cache=cache,
ambiguous=ambiguous,
)
elif dtype == Time:
return self.to_time(format, strict=strict, cache=cache)
else:
msg = "`dtype` must be of type {Date, Datetime, Time}"
raise ValueError(msg)
@deprecate_nonkeyword_arguments(allowed_args=["self"], version="1.20.0")
@unstable()
def to_decimal(self, *, scale: int) -> Expr:
"""
Convert a String column into a Decimal column.
.. warning::
This functionality is considered **unstable**. It may be changed
at any point without it being considered a breaking change.
.. versionchanged:: 1.20.0
Parameter `inference_length` should now be passed as a keyword argument.
.. versionchanged:: 1.33.0
Parameter `inference_length` was removed and `scale` was made non-optional.
Parameters
----------
scale
Number of digits after the comma to use for the decimals.
Examples
--------
>>> df = pl.DataFrame(
... {
... "numbers": [
... "40.12",
... "3420.13",
... "120134.19",
... "3212.98",
... "12.90",
... "143.09",
... "143.9",
... ]
... }
... )
>>> df.with_columns(numbers_decimal=pl.col("numbers").str.to_decimal(scale=2))
shape: (7, 2)
┌───────────┬─────────────────┐
│ numbers ┆ numbers_decimal │
│ --- ┆ --- │
│ str ┆ decimal[38,2] │
╞═══════════╪═════════════════╡
│ 40.12 ┆ 40.12 │
│ 3420.13 ┆ 3420.13 │
│ 120134.19 ┆ 120134.19 │
│ 3212.98 ┆ 3212.98 │
│ 12.90 ┆ 12.90 │
│ 143.09 ┆ 143.09 │
│ 143.9 ┆ 143.90 │
└───────────┴─────────────────┘
"""
return wrap_expr(self._pyexpr.str_to_decimal(scale=scale))
def len_bytes(self) -> Expr:
"""
Return the length of each string as the number of bytes.
Returns
-------
Expr
Expression of data type :class:`UInt32`.
See Also
--------
len_chars
Notes
-----
When working with non-ASCII text, the length in bytes is not the same as the
length in characters. You may want to use :func:`len_chars` instead.
Note that :func:`len_bytes` is much more performant (_O(1)_) than
:func:`len_chars` (_O(n)_).
Examples
--------
>>> df = pl.DataFrame({"a": ["Café", "345", "東京", None]})
>>> df.with_columns(
... pl.col("a").str.len_bytes().alias("n_bytes"),
... pl.col("a").str.len_chars().alias("n_chars"),
... )
shape: (4, 3)
┌──────┬─────────┬─────────┐
│ a ┆ n_bytes ┆ n_chars │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞══════╪═════════╪═════════╡
│ Café ┆ 5 ┆ 4 │
│ 345 ┆ 3 ┆ 3 │
│ 東京 ┆ 6 ┆ 2 │
│ null ┆ null ┆ null │
└──────┴─────────┴─────────┘
"""
return wrap_expr(self._pyexpr.str_len_bytes())
def len_chars(self) -> Expr:
"""
Return the length of each string as the number of characters.
Returns
-------
Expr
Expression of data type :class:`UInt32`.
See Also
--------
len_bytes
Notes
-----
When working with ASCII text, use :func:`len_bytes` instead to achieve
equivalent output with much better performance:
:func:`len_bytes` runs in _O(1)_, while :func:`len_chars` runs in (_O(n)_).
A character is defined as a `Unicode scalar value`_. A single character is
represented by a single byte when working with ASCII text, and a maximum of
4 bytes otherwise.
.. _Unicode scalar value: https://www.unicode.org/glossary/#unicode_scalar_value
Examples
--------
>>> df = pl.DataFrame({"a": ["Café", "345", "東京", None]})
>>> df.with_columns(
... pl.col("a").str.len_chars().alias("n_chars"),
... pl.col("a").str.len_bytes().alias("n_bytes"),
... )
shape: (4, 3)
┌──────┬─────────┬─────────┐
│ a ┆ n_chars ┆ n_bytes │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞══════╪═════════╪═════════╡
│ Café ┆ 4 ┆ 5 │
│ 345 ┆ 3 ┆ 3 │
│ 東京 ┆ 2 ┆ 6 │
│ null ┆ null ┆ null │
└──────┴─────────┴─────────┘
"""
return wrap_expr(self._pyexpr.str_len_chars())
def to_uppercase(self) -> Expr:
"""
Modify strings to their uppercase equivalent.
Examples
--------
>>> df = pl.DataFrame({"foo": ["cat", "dog"]})
>>> df.with_columns(foo_upper=pl.col("foo").str.to_uppercase())
shape: (2, 2)
┌─────┬───────────┐
│ foo ┆ foo_upper │
│ --- ┆ --- │
│ str ┆ str │
╞═════╪═══════════╡
│ cat ┆ CAT │
│ dog ┆ DOG │
└─────┴───────────┘
"""
return wrap_expr(self._pyexpr.str_to_uppercase())
def to_lowercase(self) -> Expr:
"""
Modify strings to their lowercase equivalent.
Examples
--------
>>> df = pl.DataFrame({"foo": ["CAT", "DOG"]})
>>> df.with_columns(foo_lower=pl.col("foo").str.to_lowercase())
shape: (2, 2)
┌─────┬───────────┐
│ foo ┆ foo_lower │
│ --- ┆ --- │
│ str ┆ str │
╞═════╪═══════════╡
│ CAT ┆ cat │
│ DOG ┆ dog │
└─────┴───────────┘
"""
return wrap_expr(self._pyexpr.str_to_lowercase())
def to_titlecase(self) -> Expr:
"""
Modify strings to their titlecase equivalent.
Notes
-----
This is a form of case transform where the first letter of each word is
capitalized, with the rest of the word in lowercase. Non-alphanumeric
characters define the word boundaries.
Examples
--------
>>> df = pl.DataFrame(
... {
... "quotes": [
... "'e.t. phone home'",
... "you talkin' to me?",
... "to infinity,and BEYOND!",
... ]
... }
... )
>>> df.with_columns(
... quotes_title=pl.col("quotes").str.to_titlecase(),
... )
shape: (3, 2)
┌─────────────────────────┬─────────────────────────┐
│ quotes ┆ quotes_title │
│ --- ┆ --- │
│ str ┆ str │
╞═════════════════════════╪═════════════════════════╡
│ 'e.t. phone home' ┆ 'E.T. Phone Home' │
│ you talkin' to me? ┆ You Talkin' To Me? │
│ to infinity,and BEYOND! ┆ To Infinity,And Beyond! │
└─────────────────────────┴─────────────────────────┘
"""
return wrap_expr(self._pyexpr.str_to_titlecase())
def strip_chars(self, characters: IntoExpr = None) -> Expr:
r"""
Remove leading and trailing characters.
Parameters
----------
characters
The set of characters to be removed. All combinations of this set of
characters will be stripped from the start and end of the string. If set to
None (default), all leading and trailing whitespace is removed instead.
Examples
--------
>>> df = pl.DataFrame({"foo": [" hello", "\nworld"]})
>>> df
shape: (2, 1)
┌────────┐
│ foo │
│ --- │
│ str │
╞════════╡
│ hello │
│ │
│ world │
└────────┘
>>> df.with_columns(foo_stripped=pl.col("foo").str.strip_chars())
shape: (2, 2)
┌────────┬──────────────┐
│ foo ┆ foo_stripped │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪══════════════╡
│ hello ┆ hello │
│ ┆ world │
│ world ┆ │
└────────┴──────────────┘
Characters can be stripped by passing a string as argument. Note that whitespace
will not be stripped automatically when doing so, unless that whitespace is
also included in the string.
>>> df.with_columns(foo_stripped=pl.col("foo").str.strip_chars("ow\n"))
shape: (2, 2)
┌────────┬──────────────┐
│ foo ┆ foo_stripped │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪══════════════╡
│ hello ┆ hell │
│ ┆ rld │
│ world ┆ │
└────────┴──────────────┘
"""
characters_pyexpr = parse_into_expression(characters, str_as_lit=True)
return wrap_expr(self._pyexpr.str_strip_chars(characters_pyexpr))
def strip_chars_start(self, characters: IntoExpr = None) -> Expr:
r"""
Remove leading characters.
.. note::
This method strips any characters present in `characters` from the
start of the input, no matter their order. To strip a prefix (i.e.
a "word" of characters in a certain order), use
:func:`strip_prefix` instead.
Parameters
----------
characters
The set of characters to be removed. All combinations of this set of
characters will be stripped from the start of the string. If set to None
(default), all leading whitespace is removed instead.
See Also
--------
strip_prefix
strip_chars_end
Examples
--------
>>> df = pl.DataFrame({"foo": [" hello ", "\tworld"]})
>>> df.with_columns(foo_strip_start=pl.col("foo").str.strip_chars_start())
shape: (2, 2)
┌─────────┬─────────────────┐
│ foo ┆ foo_strip_start │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪═════════════════╡
│ hello ┆ hello │
│ world ┆ world │
└─────────┴─────────────────┘
Characters can be stripped by passing a string as argument. Note that whitespace
will not be stripped automatically when doing so.
>>> df.with_columns(
... foo_strip_start=pl.col("foo").str.strip_chars_start("wod\t"),
... )
shape: (2, 2)
┌─────────┬─────────────────┐
│ foo ┆ foo_strip_start │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪═════════════════╡
│ hello ┆ hello │
│ world ┆ rld │
└─────────┴─────────────────┘
The order of the provided characters does not matter, they behave like a set.
>>> pl.DataFrame({"foo": ["aabcdef"]}).with_columns(
... foo_strip_start=pl.col("foo").str.strip_chars_start("cba")
... )
shape: (1, 2)
┌─────────┬─────────────────┐
│ foo ┆ foo_strip_start │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪═════════════════╡
│ aabcdef ┆ def │
└─────────┴─────────────────┘
"""
characters_pyexpr = parse_into_expression(characters, str_as_lit=True)
return wrap_expr(self._pyexpr.str_strip_chars_start(characters_pyexpr))
def strip_chars_end(self, characters: IntoExpr = None) -> Expr:
r"""
Remove trailing characters.
.. note::
This method strips any characters present in `characters` from the
end of the input, no matter their order. To strip a suffix (i.e.
a "word" of characters in a certain order), use
:func:`strip_suffix` instead.
Parameters
----------
characters
The set of characters to be removed. All combinations of this set of
characters will be stripped from the end of the string. If set to None
(default), all trailing whitespace is removed instead.
See Also
--------
strip_suffix
strip_chars_start
Examples
--------
>>> df = pl.DataFrame({"foo": [" hello", "world\n"]})
>>> df
shape: (2, 1)
┌────────┐
│ foo │
│ --- │
│ str │
╞════════╡
│ hello │
│ world │
│ │
└────────┘
>>> df.with_columns(foo_strip_end=pl.col("foo").str.strip_chars_end())
shape: (2, 2)
┌────────┬───────────────┐
│ foo ┆ foo_strip_end │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪═══════════════╡
│ hello ┆ hello │
│ world ┆ world │
│ ┆ │
└────────┴───────────────┘
Characters can be stripped by passing a string as argument. Note that whitespace
will not be stripped automatically when doing so, unless that whitespace is
also included in the string.
>>> df.with_columns(foo_strip_end=pl.col("foo").str.strip_chars_end("oldw "))
shape: (2, 2)
┌────────┬───────────────┐
│ foo ┆ foo_strip_end │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪═══════════════╡
│ hello ┆ he │
│ world ┆ world │
│ ┆ │
└────────┴───────────────┘
The order of the provided characters does not matter, they behave like a set.
>>> pl.DataFrame({"foo": ["abcdeff"]}).with_columns(
... foo_strip_end=pl.col("foo").str.strip_chars_end("fed")
... )
shape: (1, 2)
┌─────────┬───────────────┐
│ foo ┆ foo_strip_end │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪═══════════════╡
│ abcdeff ┆ abc │
└─────────┴───────────────┘
"""
characters_pyexpr = parse_into_expression(characters, str_as_lit=True)
return wrap_expr(self._pyexpr.str_strip_chars_end(characters_pyexpr))
def strip_prefix(self, prefix: IntoExpr) -> Expr:
"""
Remove prefix.
The prefix will be removed from the string exactly once, if found.
.. note::
This method strips the exact character sequence provided in
`prefix` from the start of the input. To strip a set of characters
in any order, use :func:`strip_chars_start` instead.
Parameters
----------
prefix
The prefix to be removed.
See Also
--------
strip_chars_start
strip_suffix
Examples
--------
>>> df = pl.DataFrame({"a": ["foobar", "foofoobar", "foo", "bar"]})
>>> df.with_columns(pl.col("a").str.strip_prefix("foo").alias("stripped"))
shape: (4, 2)
┌───────────┬──────────┐
│ a ┆ stripped │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════╪══════════╡
│ foobar ┆ bar │
│ foofoobar ┆ foobar │
│ foo ┆ │
│ bar ┆ bar │
└───────────┴──────────┘
"""
prefix_pyexpr = parse_into_expression(prefix, str_as_lit=True)
return wrap_expr(self._pyexpr.str_strip_prefix(prefix_pyexpr))
def strip_suffix(self, suffix: IntoExpr) -> Expr:
"""
Remove suffix.
The suffix will be removed from the string exactly once, if found.
.. note::
This method strips the exact character sequence provided in
`suffix` from the end of the input. To strip a set of characters
in any order, use :func:`strip_chars_end` instead.
Parameters
----------
suffix
The suffix to be removed.
See Also
--------
strip_chars_end
strip_prefix
Examples
--------
>>> df = pl.DataFrame({"a": ["foobar", "foobarbar", "foo", "bar"]})
>>> df.with_columns(pl.col("a").str.strip_suffix("bar").alias("stripped"))
shape: (4, 2)
┌───────────┬──────────┐
│ a ┆ stripped │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════╪══════════╡
│ foobar ┆ foo │
│ foobarbar ┆ foobar │
│ foo ┆ foo │
│ bar ┆ │
└───────────┴──────────┘
"""
suffix_pyexpr = parse_into_expression(suffix, str_as_lit=True)
return wrap_expr(self._pyexpr.str_strip_suffix(suffix_pyexpr))
def pad_start(self, length: int | IntoExprColumn, fill_char: str = " ") -> Expr:
"""
Pad the start of the string until it reaches the given length.
Parameters
----------
length
Pad the string until it reaches this length. Strings with length equal to or
greater than this value are returned as-is.
fill_char
The character to pad the string with.
See Also
--------
pad_end
zfill
Examples
--------
>>> df = pl.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]})
>>> df.with_columns(padded=pl.col("a").str.pad_start(8, "*"))
shape: (4, 2)
┌──────────────┬──────────────┐
│ a ┆ padded │
│ --- ┆ --- │
│ str ┆ str │
╞══════════════╪══════════════╡
│ cow ┆ *****cow │
│ monkey ┆ **monkey │
│ hippopotamus ┆ hippopotamus │
│ null ┆ null │
└──────────────┴──────────────┘
"""
length_pyexpr = parse_into_expression(length)
if not isinstance(fill_char, str):
msg = f'"pad_start" expects a `str`, given a {qualified_type_name(fill_char)!r}'
raise TypeError(msg)
return wrap_expr(self._pyexpr.str_pad_start(length_pyexpr, fill_char))
def pad_end(self, length: int | IntoExprColumn, fill_char: str = " ") -> Expr:
"""
Pad the end of the string until it reaches the given length.
Parameters
----------
length
Pad the string until it reaches this length. Strings with length equal to or
greater than this value are returned as-is. Can be int or expression.
fill_char
The character to pad the string with.
See Also
--------
pad_start
Examples
--------
>>> df = pl.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]})
>>> df.with_columns(padded=pl.col("a").str.pad_end(8, "*"))
shape: (4, 2)
┌──────────────┬──────────────┐
│ a ┆ padded │
│ --- ┆ --- │
│ str ┆ str │
╞══════════════╪══════════════╡
│ cow ┆ cow***** │
│ monkey ┆ monkey** │
│ hippopotamus ┆ hippopotamus │
│ null ┆ null │
└──────────────┴──────────────┘
"""
length_pyexpr = parse_into_expression(length)
if not isinstance(fill_char, str):
msg = (
f'"pad_end" expects a `str`, given a {qualified_type_name(fill_char)!r}'
)
raise TypeError(msg)
return wrap_expr(self._pyexpr.str_pad_end(length_pyexpr, fill_char))
def zfill(self, length: int | IntoExprColumn) -> Expr:
"""
Pad the start of the string with zeros until it reaches the given length.
A sign prefix (`-`) is handled by inserting the padding after the sign
character rather than before.
Parameters
----------
length
Pad the string until it reaches this length. Strings with length equal to
or greater than this value are returned as-is.
See Also
--------
pad_start
Notes
-----
This method is intended for padding numeric strings. If your data contains
non-ASCII characters, use :func:`pad_start` instead.
Examples
--------
>>> df = pl.DataFrame({"a": [-1, 123, 999999, None]})
>>> df.with_columns(zfill=pl.col("a").cast(pl.String).str.zfill(4))
shape: (4, 2)
┌────────┬────────┐
│ a ┆ zfill │
│ --- ┆ --- │
│ i64 ┆ str │
╞════════╪════════╡
│ -1 ┆ -001 │
│ 123 ┆ 0123 │
│ 999999 ┆ 999999 │
│ null ┆ null │
└────────┴────────┘
>>> df = pl.DataFrame(
... {
... "a": [-1, 123, 999999, None],
... "length": [8, 4, 1, 2],
... }
... )
>>> df.with_columns(zfill=pl.col("a").cast(pl.String).str.zfill("length"))
shape: (4, 3)
┌────────┬────────┬──────────┐
│ a ┆ length ┆ zfill │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞════════╪════════╪══════════╡
│ -1 ┆ 8 ┆ -0000001 │
│ 123 ┆ 4 ┆ 0123 │
│ 999999 ┆ 1 ┆ 999999 │
│ null ┆ 2 ┆ null │
└────────┴────────┴──────────┘
"""
length_pyexpr = parse_into_expression(length)
return wrap_expr(self._pyexpr.str_zfill(length_pyexpr))
def contains(
self, pattern: str | Expr, *, literal: bool = False, strict: bool = True
) -> Expr:
"""
Check if the string contains a substring that matches a pattern.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
literal
Treat `pattern` as a literal string, not as a regular expression.
strict
Raise an error if the underlying pattern is not a valid regex,
otherwise mask out with a null value.
Notes
-----
To modify regular expression behaviour (such as case-sensitivity) with
flags, use the inline `(?iLmsuxU)` syntax. For example:
>>> pl.DataFrame({"s": ["AAA", "aAa", "aaa"]}).with_columns(
... default_match=pl.col("s").str.contains("AA"),
... insensitive_match=pl.col("s").str.contains("(?i)AA"),
... )
shape: (3, 3)
┌─────┬───────────────┬───────────────────┐
│ s ┆ default_match ┆ insensitive_match │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool │
╞═════╪═══════════════╪═══════════════════╡
│ AAA ┆ true ┆ true │
│ aAa ┆ false ┆ true │
│ aaa ┆ false ┆ true │
└─────┴───────────────┴───────────────────┘
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
See Also
--------
starts_with : Check if string values start with a substring.
ends_with : Check if string values end with a substring.
find: Return the index of the first substring matching a pattern.
Examples
--------
>>> df = pl.DataFrame({"txt": ["Crab", "cat and dog", "rab$bit", None]})
>>> df.select(
... pl.col("txt"),
... pl.col("txt").str.contains("cat|bit").alias("regex"),
... pl.col("txt").str.contains("rab$", literal=True).alias("literal"),
... )
shape: (4, 3)
┌─────────────┬───────┬─────────┐
│ txt ┆ regex ┆ literal │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool │
╞═════════════╪═══════╪═════════╡
│ Crab ┆ false ┆ false │
│ cat and dog ┆ true ┆ false │
│ rab$bit ┆ true ┆ true │
│ null ┆ null ┆ null │
└─────────────┴───────┴─────────┘
"""
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
return wrap_expr(self._pyexpr.str_contains(pattern_pyexpr, literal, strict))
def find(
self, pattern: str | Expr, *, literal: bool = False, strict: bool = True
) -> Expr:
"""
Return the bytes offset of the first substring matching a pattern.
If the pattern is not found, returns None.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
literal
Treat `pattern` as a literal string, not as a regular expression.
strict
Raise an error if the underlying pattern is not a valid regex,
otherwise mask out with a null value.
Notes
-----
To modify regular expression behaviour (such as case-sensitivity) with
flags, use the inline `(?iLmsuxU)` syntax. For example:
>>> pl.DataFrame({"s": ["AAA", "aAa", "aaa"]}).with_columns(
... default_match=pl.col("s").str.find("Aa"),
... insensitive_match=pl.col("s").str.find("(?i)Aa"),
... )
shape: (3, 3)
┌─────┬───────────────┬───────────────────┐
│ s ┆ default_match ┆ insensitive_match │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞═════╪═══════════════╪═══════════════════╡
│ AAA ┆ null ┆ 0 │
│ aAa ┆ 1 ┆ 0 │
│ aaa ┆ null ┆ 0 │
└─────┴───────────────┴───────────────────┘
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
See Also
--------
contains : Check if the string contains a substring that matches a pattern.
Examples
--------
>>> df = pl.DataFrame(
... {
... "txt": ["Crab", "Lobster", None, "Crustacean"],
... "pat": ["a[bc]", "b.t", "[aeiuo]", "(?i)A[BC]"],
... }
... )
Find the index of the first substring matching a regex or literal pattern:
>>> df.select(
... pl.col("txt"),
... pl.col("txt").str.find("a|e").alias("a|e (regex)"),
... pl.col("txt").str.find("e", literal=True).alias("e (lit)"),
... )
shape: (4, 3)
┌────────────┬─────────────┬─────────┐
│ txt ┆ a|e (regex) ┆ e (lit) │
│ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 │
╞════════════╪═════════════╪═════════╡
│ Crab ┆ 2 ┆ null │
│ Lobster ┆ 5 ┆ 5 │
│ null ┆ null ┆ null │
│ Crustacean ┆ 5 ┆ 7 │
└────────────┴─────────────┴─────────┘
Match against a pattern found in another column or (expression):
>>> df.with_columns(pl.col("txt").str.find(pl.col("pat")).alias("find_pat"))
shape: (4, 3)
┌────────────┬───────────┬──────────┐
│ txt ┆ pat ┆ find_pat │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞════════════╪═══════════╪══════════╡
│ Crab ┆ a[bc] ┆ 2 │
│ Lobster ┆ b.t ┆ 2 │
│ null ┆ [aeiuo] ┆ null │
│ Crustacean ┆ (?i)A[BC] ┆ 5 │
└────────────┴───────────┴──────────┘
"""
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
return wrap_expr(self._pyexpr.str_find(pattern_pyexpr, literal, strict))
def ends_with(self, suffix: str | Expr) -> Expr:
"""
Check if string values end with a substring.
Parameters
----------
suffix
Suffix substring.
See Also
--------
contains : Check if the string contains a substring that matches a pattern.
starts_with : Check if string values start with a substring.
Examples
--------
>>> df = pl.DataFrame({"fruits": ["apple", "mango", None]})
>>> df.with_columns(
... pl.col("fruits").str.ends_with("go").alias("has_suffix"),
... )
shape: (3, 2)
┌────────┬────────────┐
│ fruits ┆ has_suffix │
│ --- ┆ --- │
│ str ┆ bool │
╞════════╪════════════╡
│ apple ┆ false │
│ mango ┆ true │
│ null ┆ null │
└────────┴────────────┘
>>> df = pl.DataFrame(
... {"fruits": ["apple", "mango", "banana"], "suffix": ["le", "go", "nu"]}
... )
>>> df.with_columns(
... pl.col("fruits").str.ends_with(pl.col("suffix")).alias("has_suffix"),
... )
shape: (3, 3)
┌────────┬────────┬────────────┐
│ fruits ┆ suffix ┆ has_suffix │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ bool │
╞════════╪════════╪════════════╡
│ apple ┆ le ┆ true │
│ mango ┆ go ┆ true │
│ banana ┆ nu ┆ false │
└────────┴────────┴────────────┘
Using `ends_with` as a filter condition:
>>> df.filter(pl.col("fruits").str.ends_with("go"))
shape: (1, 2)
┌────────┬────────┐
│ fruits ┆ suffix │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪════════╡
│ mango ┆ go │
└────────┴────────┘
"""
suffix_pyexpr = parse_into_expression(suffix, str_as_lit=True)
return wrap_expr(self._pyexpr.str_ends_with(suffix_pyexpr))
def starts_with(self, prefix: str | Expr) -> Expr:
"""
Check if string values start with a substring.
Parameters
----------
prefix
Prefix substring.
See Also
--------
contains : Check if the string contains a substring that matches a pattern.
ends_with : Check if string values end with a substring.
Examples
--------
>>> df = pl.DataFrame({"fruits": ["apple", "mango", None]})
>>> df.with_columns(
... pl.col("fruits").str.starts_with("app").alias("has_prefix"),
... )
shape: (3, 2)
┌────────┬────────────┐
│ fruits ┆ has_prefix │
│ --- ┆ --- │
│ str ┆ bool │
╞════════╪════════════╡
│ apple ┆ true │
│ mango ┆ false │
│ null ┆ null │
└────────┴────────────┘
>>> df = pl.DataFrame(
... {"fruits": ["apple", "mango", "banana"], "prefix": ["app", "na", "ba"]}
... )
>>> df.with_columns(
... pl.col("fruits").str.starts_with(pl.col("prefix")).alias("has_prefix"),
... )
shape: (3, 3)
┌────────┬────────┬────────────┐
│ fruits ┆ prefix ┆ has_prefix │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ bool │
╞════════╪════════╪════════════╡
│ apple ┆ app ┆ true │
│ mango ┆ na ┆ false │
│ banana ┆ ba ┆ true │
└────────┴────────┴────────────┘
Using `starts_with` as a filter condition:
>>> df.filter(pl.col("fruits").str.starts_with("app"))
shape: (1, 2)
┌────────┬────────┐
│ fruits ┆ prefix │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪════════╡
│ apple ┆ app │
└────────┴────────┘
"""
prefix_pyexpr = parse_into_expression(prefix, str_as_lit=True)
return wrap_expr(self._pyexpr.str_starts_with(prefix_pyexpr))
def json_decode(
self,
dtype: PolarsDataType | pl.DataTypeExpr,
*,
infer_schema_length: int | None = None,
) -> Expr:
"""
Parse string values as JSON.
Throws an error if invalid JSON strings are encountered.
Parameters
----------
dtype
The dtype to cast the extracted value to.
infer_schema_length
Deprecated and ignored.
.. versionchanged:: 1.33.0
Deprecate `infer_schema_length` and make `dtype` non-optional to
ensure that the planner can determine the output datatype.
See Also
--------
json_path_match : Extract the first match from a JSON string using the provided
JSONPath.
Examples
--------
>>> df = pl.DataFrame(
... {"json": ['{"a":1, "b": true}', None, '{"a":2, "b": false}']}
... )
>>> dtype = pl.Struct([pl.Field("a", pl.Int64), pl.Field("b", pl.Boolean)])
>>> df.with_columns(decoded=pl.col("json").str.json_decode(dtype))
shape: (3, 2)
┌─────────────────────┬───────────┐
│ json ┆ decoded │
│ --- ┆ --- │
│ str ┆ struct[2] │
╞═════════════════════╪═══════════╡
│ {"a":1, "b": true} ┆ {1,true} │
│ null ┆ null │
│ {"a":2, "b": false} ┆ {2,false} │
└─────────────────────┴───────────┘
"""
if dtype is None:
msg = "`Expr.str.json_decode` needs an explicitly given `dtype` otherwise Polars is not able to determine the output type. If you want to eagerly infer datatype you can use `Series.str.json_decode`."
raise TypeError(msg)
if infer_schema_length is not None:
issue_warning(
"`Expr.str.json_decode` with `infer_schema_length` is deprecated and has no effect on execution.",
DeprecationWarning,
)
dtype_expr = parse_into_datatype_expr(dtype)._pydatatype_expr
return wrap_expr(self._pyexpr.str_json_decode(dtype_expr))
def json_path_match(self, json_path: IntoExprColumn) -> Expr:
"""
Extract the first match from a JSON string using the provided JSONPath.
Throws errors if invalid JSON strings are encountered. All return values
are cast to :class:`String`, regardless of the original value.
Documentation on the JSONPath standard can be found
`here <https://goessner.net/articles/JsonPath/>`_.
Parameters
----------
json_path
A valid JSONPath query string.
Returns
-------
Expr
Expression of data type :class:`String`. Contains null values if original
value is null or the json_path returns nothing.
Examples
--------
>>> df = pl.DataFrame(
... {"json_val": ['{"a":"1"}', None, '{"a":2}', '{"a":2.1}', '{"a":true}']}
... )
>>> df.with_columns(matched=pl.col("json_val").str.json_path_match("$.a"))
shape: (5, 2)
┌────────────┬─────────┐
│ json_val ┆ matched │
│ --- ┆ --- │
│ str ┆ str │
╞════════════╪═════════╡
│ {"a":"1"} ┆ 1 │
│ null ┆ null │
│ {"a":2} ┆ 2 │
│ {"a":2.1} ┆ 2.1 │
│ {"a":true} ┆ true │
└────────────┴─────────┘
"""
json_path_pyexpr = parse_into_expression(json_path, str_as_lit=True)
return wrap_expr(self._pyexpr.str_json_path_match(json_path_pyexpr))
def decode(self, encoding: TransferEncoding, *, strict: bool = True) -> Expr:
r"""
Decode values using the provided encoding.
Parameters
----------
encoding : {'hex', 'base64'}
The encoding to use.
strict
Raise an error if the underlying value cannot be decoded,
otherwise mask out with a null value.
Returns
-------
Expr
Expression of data type :class:`Binary`.
Examples
--------
>>> df = pl.DataFrame({"color": ["000000", "ffff00", "0000ff"]})
>>> df.with_columns(pl.col("color").str.decode("hex").alias("decoded"))
shape: (3, 2)
┌────────┬─────────────────┐
│ color ┆ decoded │
│ --- ┆ --- │
│ str ┆ binary │
╞════════╪═════════════════╡
│ 000000 ┆ b"\x00\x00\x00" │
│ ffff00 ┆ b"\xff\xff\x00" │
│ 0000ff ┆ b"\x00\x00\xff" │
└────────┴─────────────────┘
"""
if encoding == "hex":
return wrap_expr(self._pyexpr.str_hex_decode(strict))
elif encoding == "base64":
return wrap_expr(self._pyexpr.str_base64_decode(strict))
else:
msg = f"`encoding` must be one of {{'hex', 'base64'}}, got {encoding!r}"
raise ValueError(msg)
def encode(self, encoding: TransferEncoding) -> Expr:
"""
Encode values using the provided encoding.
Parameters
----------
encoding : {'hex', 'base64'}
The encoding to use.
Returns
-------
Expr
Expression of data type :class:`String`.
Examples
--------
>>> df = pl.DataFrame({"strings": ["foo", "bar", None]})
>>> df.with_columns(strings_hex=pl.col("strings").str.encode("hex"))
shape: (3, 2)
┌─────────┬─────────────┐
│ strings ┆ strings_hex │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪═════════════╡
│ foo ┆ 666f6f │
│ bar ┆ 626172 │
│ null ┆ null │
└─────────┴─────────────┘
"""
if encoding == "hex":
return wrap_expr(self._pyexpr.str_hex_encode())
elif encoding == "base64":
return wrap_expr(self._pyexpr.str_base64_encode())
else:
msg = f"`encoding` must be one of {{'hex', 'base64'}}, got {encoding!r}"
raise ValueError(msg)
def extract(self, pattern: IntoExprColumn, group_index: int = 1) -> Expr:
r"""
Extract the target capture group from provided patterns.
Parameters
----------
pattern
A valid regular expression pattern containing at least one capture group,
compatible with the `regex crate <https://docs.rs/regex/latest/regex/>`_.
group_index
Index of the targeted capture group.
Group 0 means the whole pattern, the first group begins at index 1.
Defaults to the first capture group.
Notes
-----
To modify regular expression behaviour (such as multi-line matching)
with flags, use the inline `(?iLmsuxU)` syntax. For example:
>>> df = pl.DataFrame(
... data={
... "lines": [
... "I Like\nThose\nOdds",
... "This is\nThe Way",
... ]
... }
... )
>>> df.with_columns(
... pl.col("lines").str.extract(r"(?m)^(T\w+)", 1).alias("matches"),
... )
shape: (2, 2)
┌─────────┬─────────┐
│ lines ┆ matches │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪═════════╡
│ I Like ┆ Those │
│ Those ┆ │
│ Odds ┆ │
│ This is ┆ This │
│ The Way ┆ │
└─────────┴─────────┘
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
Returns
-------
Expr
Expression of data type :class:`String`. Contains null values if original
value is null or the regex captures nothing.
Examples
--------
>>> df = pl.DataFrame(
... {
... "url": [
... "http://vote.com/ballon_dor?error=404&ref=unknown",
... "http://vote.com/ballon_dor?ref=polars&candidate=messi",
... "http://vote.com/ballon_dor?candidate=ronaldo&ref=polars",
... ]
... }
... )
>>> df.select(
... pl.col("url").str.extract(r"candidate=(\w+)", 1).alias("candidate"),
... pl.col("url").str.extract(r"ref=(\w+)", 1).alias("referer"),
... pl.col("url").str.extract(r"error=(\w+)", 1).alias("error"),
... )
shape: (3, 3)
┌───────────┬─────────┬───────┐
│ candidate ┆ referer ┆ error │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═══════════╪═════════╪═══════╡
│ null ┆ unknown ┆ 404 │
│ messi ┆ polars ┆ null │
│ ronaldo ┆ polars ┆ null │
└───────────┴─────────┴───────┘
"""
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
return wrap_expr(self._pyexpr.str_extract(pattern_pyexpr, group_index))
def extract_all(self, pattern: str | Expr) -> Expr:
r'''
Extract all matches for the given regex pattern.
Extract each successive non-overlapping regex match in an individual string
as a list. If the haystack string is `null`, `null` is returned.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
Notes
-----
To modify regular expression behaviour (such as "verbose" mode and/or
case-sensitive matching) with flags, use the inline `(?iLmsuxU)` syntax.
For example:
>>> df = pl.DataFrame(
... data={
... "email": [
... "real.email@spam.com",
... "some_account@somewhere.net",
... "abc.def.ghi.jkl@uvw.xyz.co.uk",
... ]
... }
... )
>>> # extract name/domain parts from the addresses, using verbose regex
>>> df.with_columns(
... pl.col("email")
... .str.extract_all(
... r"""(?xi) # activate 'verbose' and 'case-insensitive' flags
... [ # (start character group)
... A-Z # letters
... 0-9 # digits
... ._%+\- # special chars
... ] # (end character group)
... + # 'one or more' quantifier
... """
... )
... .list.to_struct(fields=["name", "domain"])
... .alias("email_parts")
... ).unnest("email_parts")
shape: (3, 3)
┌───────────────────────────────┬─────────────────┬───────────────┐
│ email ┆ name ┆ domain │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═══════════════════════════════╪═════════════════╪═══════════════╡
│ real.email@spam.com ┆ real.email ┆ spam.com │
│ some_account@somewhere.net ┆ some_account ┆ somewhere.net │
│ abc.def.ghi.jkl@uvw.xyz.co.uk ┆ abc.def.ghi.jkl ┆ uvw.xyz.co.uk │
└───────────────────────────────┴─────────────────┴───────────────┘
See the regex crate's section on `grouping and flags
<https://docs.rs/regex/latest/regex/#grouping-and-flags>`_ for
additional information about the use of inline expression modifiers.
Returns
-------
Expr
Expression of data type `List(String)`.
Examples
--------
>>> df = pl.DataFrame({"foo": ["123 bla 45 asd", "xyz 678 910t", "bar", None]})
>>> df.select(
... pl.col("foo").str.extract_all(r"\d+").alias("extracted_nrs"),
... )
shape: (4, 1)
┌────────────────┐
│ extracted_nrs │
│ --- │
│ list[str] │
╞════════════════╡
│ ["123", "45"] │
│ ["678", "910"] │
│ [] │
│ null │
└────────────────┘
'''
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
return wrap_expr(self._pyexpr.str_extract_all(pattern_pyexpr))
def extract_groups(self, pattern: str) -> Expr:
r"""
Extract all capture groups for the given regex pattern.
Parameters
----------
pattern
A valid regular expression pattern containing at least one capture group,
compatible with the `regex crate <https://docs.rs/regex/latest/regex/>`_.
Notes
-----
All group names are **strings**.
If your pattern contains unnamed groups, their numerical position is converted
to a string.
For example, here we access groups 2 and 3 via the names `"2"` and `"3"`::
>>> df = pl.DataFrame({"col": ["foo bar baz"]})
>>> (
... df.with_columns(
... pl.col("col").str.extract_groups(r"(\S+) (\S+) (.+)")
... ).select(pl.col("col").struct["2"], pl.col("col").struct["3"])
... )
shape: (1, 2)
┌─────┬─────┐
│ 2 ┆ 3 │
│ --- ┆ --- │
│ str ┆ str │
╞═════╪═════╡
│ bar ┆ baz │
└─────┴─────┘
Returns
-------
Expr
Expression of data type :class:`Struct` with fields of data type
:class:`String`.
Examples
--------
>>> df = pl.DataFrame(
... data={
... "url": [
... "http://vote.com/ballon_dor?candidate=messi&ref=python",
... "http://vote.com/ballon_dor?candidate=weghorst&ref=polars",
... "http://vote.com/ballon_dor?error=404&ref=rust",
... ]
... }
... )
>>> pattern = r"candidate=(?<candidate>\w+)&ref=(?<ref>\w+)"
>>> df.select(captures=pl.col("url").str.extract_groups(pattern)).unnest(
... "captures"
... )
shape: (3, 2)
┌───────────┬────────┐
│ candidate ┆ ref │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════╪════════╡
│ messi ┆ python │
│ weghorst ┆ polars │
│ null ┆ null │
└───────────┴────────┘
Unnamed groups have their numerical position converted to a string:
>>> pattern = r"candidate=(\w+)&ref=(\w+)"
>>> (
... df.with_columns(
... captures=pl.col("url").str.extract_groups(pattern)
... ).with_columns(name=pl.col("captures").struct["1"].str.to_uppercase())
... )
shape: (3, 3)
┌─────────────────────────────────┬───────────────────────┬──────────┐
│ url ┆ captures ┆ name │
│ --- ┆ --- ┆ --- │
│ str ┆ struct[2] ┆ str │
╞═════════════════════════════════╪═══════════════════════╪══════════╡
│ http://vote.com/ballon_dor?can… ┆ {"messi","python"} ┆ MESSI │
│ http://vote.com/ballon_dor?can… ┆ {"weghorst","polars"} ┆ WEGHORST │
│ http://vote.com/ballon_dor?err… ┆ {null,null} ┆ null │
└─────────────────────────────────┴───────────────────────┴──────────┘
"""
if not isinstance(pattern, str):
msg = f'"extract_groups" expects a `str`, given a {qualified_type_name(pattern)!r}'
raise TypeError(msg)
return wrap_expr(self._pyexpr.str_extract_groups(pattern))
def count_matches(self, pattern: str | Expr, *, literal: bool = False) -> Expr:
r"""
Count all successive non-overlapping regex matches.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
literal
Treat `pattern` as a literal string, not as a regular expression.
Returns
-------
Expr
Expression of data type :class:`UInt32`. Returns null if the
original value is null.
Examples
--------
>>> df = pl.DataFrame({"foo": ["123 bla 45 asd", "xyz 678 910t", "bar", None]})
>>> df.with_columns(
... pl.col("foo").str.count_matches(r"\d").alias("count_digits"),
... )
shape: (4, 2)
┌────────────────┬──────────────┐
│ foo ┆ count_digits │
│ --- ┆ --- │
│ str ┆ u32 │
╞════════════════╪══════════════╡
│ 123 bla 45 asd ┆ 5 │
│ xyz 678 910t ┆ 6 │
│ bar ┆ 0 │
│ null ┆ null │
└────────────────┴──────────────┘
>>> df = pl.DataFrame({"bar": ["12 dbc 3xy", "cat\\w", "1zy3\\d\\d", None]})
>>> df.with_columns(
... pl.col("bar")
... .str.count_matches(r"\d", literal=True)
... .alias("count_digits"),
... )
shape: (4, 2)
┌────────────┬──────────────┐
│ bar ┆ count_digits │
│ --- ┆ --- │
│ str ┆ u32 │
╞════════════╪══════════════╡
│ 12 dbc 3xy ┆ 0 │
│ cat\w ┆ 0 │
│ 1zy3\d\d ┆ 2 │
│ null ┆ null │
└────────────┴──────────────┘
"""
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
return wrap_expr(self._pyexpr.str_count_matches(pattern_pyexpr, literal))
def split(self, by: IntoExpr, *, inclusive: bool = False) -> Expr:
"""
Split the string by a substring.
Parameters
----------
by
Substring to split by.
inclusive
If True, include the split character/string in the results.
Examples
--------
>>> df = pl.DataFrame({"s": ["foo bar", "foo_bar", "foo_bar_baz"]})
>>> df.with_columns(
... pl.col("s").str.split(by="_").alias("split"),
... pl.col("s").str.split(by="_", inclusive=True).alias("split_inclusive"),
... )
shape: (3, 3)
┌─────────────┬───────────────────────┬─────────────────────────┐
│ s ┆ split ┆ split_inclusive │
│ --- ┆ --- ┆ --- │
│ str ┆ list[str] ┆ list[str] │
╞═════════════╪═══════════════════════╪═════════════════════════╡
│ foo bar ┆ ["foo bar"] ┆ ["foo bar"] │
│ foo_bar ┆ ["foo", "bar"] ┆ ["foo_", "bar"] │
│ foo_bar_baz ┆ ["foo", "bar", "baz"] ┆ ["foo_", "bar_", "baz"] │
└─────────────┴───────────────────────┴─────────────────────────┘
>>> df = pl.DataFrame(
... {"s": ["foo^bar", "foo_bar", "foo*bar*baz"], "by": ["_", "_", "*"]}
... )
>>> df.with_columns(
... pl.col("s").str.split(by=pl.col("by")).alias("split"),
... pl.col("s")
... .str.split(by=pl.col("by"), inclusive=True)
... .alias("split_inclusive"),
... )
shape: (3, 4)
┌─────────────┬─────┬───────────────────────┬─────────────────────────┐
│ s ┆ by ┆ split ┆ split_inclusive │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ list[str] ┆ list[str] │
╞═════════════╪═════╪═══════════════════════╪═════════════════════════╡
│ foo^bar ┆ _ ┆ ["foo^bar"] ┆ ["foo^bar"] │
│ foo_bar ┆ _ ┆ ["foo", "bar"] ┆ ["foo_", "bar"] │
│ foo*bar*baz ┆ * ┆ ["foo", "bar", "baz"] ┆ ["foo*", "bar*", "baz"] │
└─────────────┴─────┴───────────────────────┴─────────────────────────┘
Returns
-------
Expr
Expression of data type :class:`String`.
"""
by_pyexpr = parse_into_expression(by, str_as_lit=True)
if inclusive:
return wrap_expr(self._pyexpr.str_split_inclusive(by_pyexpr))
return wrap_expr(self._pyexpr.str_split(by_pyexpr))
def split_exact(self, by: IntoExpr, n: int, *, inclusive: bool = False) -> Expr:
"""
Split the string by a substring using `n` splits.
Results in a struct of `n+1` fields.
If it cannot make `n` splits, the remaining field elements will be null.
Parameters
----------
by
Substring to split by.
n
Number of splits to make.
inclusive
If True, include the split character/string in the results.
Returns
-------
Expr
Expression of data type :class:`Struct` with fields of data type
:class:`String`.
Examples
--------
>>> df = pl.DataFrame({"x": ["a_1", None, "c", "d_4"]})
>>> df.with_columns(
... extracted=pl.col("x").str.split_exact("_", 1).alias("fields"),
... )
shape: (4, 2)
┌──────┬─────────────┐
│ x ┆ extracted │
│ --- ┆ --- │
│ str ┆ struct[2] │
╞══════╪═════════════╡
│ a_1 ┆ {"a","1"} │
│ null ┆ {null,null} │
│ c ┆ {"c",null} │
│ d_4 ┆ {"d","4"} │
└──────┴─────────────┘
Split string values in column x in exactly 2 parts and assign
each part to a new column.
>>> df.with_columns(
... pl.col("x")
... .str.split_exact("_", 1)
... .struct.rename_fields(["first_part", "second_part"])
... .alias("fields")
... ).unnest("fields")
shape: (4, 3)
┌──────┬────────────┬─────────────┐
│ x ┆ first_part ┆ second_part │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════╪════════════╪═════════════╡
│ a_1 ┆ a ┆ 1 │
│ null ┆ null ┆ null │
│ c ┆ c ┆ null │
│ d_4 ┆ d ┆ 4 │
└──────┴────────────┴─────────────┘
"""
by_pyexpr = parse_into_expression(by, str_as_lit=True)
if inclusive:
return wrap_expr(self._pyexpr.str_split_exact_inclusive(by_pyexpr, n))
return wrap_expr(self._pyexpr.str_split_exact(by_pyexpr, n))
def splitn(self, by: IntoExpr, n: int) -> Expr:
"""
Split the string by a substring, restricted to returning at most `n` items.
If the number of possible splits is less than `n-1`, the remaining field
elements will be null. If the number of possible splits is `n-1` or greater,
the last (nth) substring will contain the remainder of the string.
Parameters
----------
by
Substring to split by.
n
Max number of items to return.
Returns
-------
Expr
Expression of data type :class:`Struct` with fields of data type
:class:`String`.
Examples
--------
>>> df = pl.DataFrame({"s": ["foo bar", None, "foo-bar", "foo bar baz"]})
>>> df.with_columns(pl.col("s").str.splitn(" ", 2).alias("fields"))
shape: (4, 2)
┌─────────────┬───────────────────┐
│ s ┆ fields │
│ --- ┆ --- │
│ str ┆ struct[2] │
╞═════════════╪═══════════════════╡
│ foo bar ┆ {"foo","bar"} │
│ null ┆ {null,null} │
│ foo-bar ┆ {"foo-bar",null} │
│ foo bar baz ┆ {"foo","bar baz"} │
└─────────────┴───────────────────┘
Split string values in column s in exactly 2 parts and assign
each part to a new column.
>>> df.with_columns(
... pl.col("s")
... .str.splitn(" ", 2)
... .struct.rename_fields(["first_part", "second_part"])
... .alias("fields")
... ).unnest("fields")
shape: (4, 3)
┌─────────────┬────────────┬─────────────┐
│ s ┆ first_part ┆ second_part │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════════════╪════════════╪═════════════╡
│ foo bar ┆ foo ┆ bar │
│ null ┆ null ┆ null │
│ foo-bar ┆ foo-bar ┆ null │
│ foo bar baz ┆ foo ┆ bar baz │
└─────────────┴────────────┴─────────────┘
"""
by_pyexpr = parse_into_expression(by, str_as_lit=True)
return wrap_expr(self._pyexpr.str_splitn(by_pyexpr, n))
def replace(
self,
pattern: str | Expr,
value: str | Expr,
*,
literal: bool = False,
n: int = 1,
) -> Expr:
r"""
Replace first matching regex/literal substring with a new string value.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
value
String that will replace the matched substring.
literal
Treat `pattern` as a literal string, not a regex.
n
Number of matches to replace.
See Also
--------
replace_all
Notes
-----
* To modify regular expression behaviour (such as case-sensitivity) with flags,
use the inline `(?iLmsuxU)` syntax. See the regex crate's section on
`grouping and flags <https://docs.rs/regex/latest/regex/#grouping-and-flags>`_
for additional information about the use of inline expression modifiers.
* The dollar sign (`$`) is a special character related to capture groups; if you
want to replace some target pattern with characters that include a literal `$`
you should escape it by doubling it up as `$$`, or set `literal=True` if you
do not need a full regular expression pattern match. Otherwise, you will be
referencing a (potentially non-existent) capture group.
In the example below we need to double up `$` (to represent a literal dollar
sign, and then refer to the capture group using `$n` or `${n}`, hence the
three consecutive `$` characters in the replacement value:
.. code-block:: python
>>> df = pl.DataFrame({"cost": ["#12.34", "#56.78"]})
>>> df.with_columns(
... cost_usd=pl.col("cost").str.replace(r"#(\d+)", "$$${1}")
... )
shape: (2, 2)
┌────────┬──────────┐
│ cost ┆ cost_usd │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪══════════╡
│ #12.34 ┆ $12.34 │
│ #56.78 ┆ $56.78 │
└────────┴──────────┘
Examples
--------
>>> df = pl.DataFrame({"id": [1, 2], "text": ["123abc", "abc456"]})
>>> df.with_columns(pl.col("text").str.replace(r"abc\b", "ABC"))
shape: (2, 2)
┌─────┬────────┐
│ id ┆ text │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪════════╡
│ 1 ┆ 123ABC │
│ 2 ┆ abc456 │
└─────┴────────┘
Capture groups are supported. Use `$1` or `${1}` in the `value` string to refer
to the first capture group in the `pattern`, `$2` or `${2}` to refer to the
second capture group, and so on. You can also use *named* capture groups.
>>> df = pl.DataFrame({"word": ["hat", "hut"]})
>>> df.with_columns(
... positional=pl.col.word.str.replace("h(.)t", "b${1}d"),
... named=pl.col.word.str.replace("h(?<vowel>.)t", "b${vowel}d"),
... )
shape: (2, 3)
┌──────┬────────────┬───────┐
│ word ┆ positional ┆ named │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════╪════════════╪═══════╡
│ hat ┆ bad ┆ bad │
│ hut ┆ bud ┆ bud │
└──────┴────────────┴───────┘
Apply case-insensitive string replacement using the `(?i)` flag.
>>> df = pl.DataFrame(
... {
... "city": "Philadelphia",
... "season": ["Spring", "Summer", "Autumn", "Winter"],
... "weather": ["Rainy", "Sunny", "Cloudy", "Snowy"],
... }
... )
>>> df.with_columns(
... pl.col("weather").str.replace(r"(?i)foggy|rainy|cloudy|snowy", "Sunny")
... )
shape: (4, 3)
┌──────────────┬────────┬─────────┐
│ city ┆ season ┆ weather │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════════════╪════════╪═════════╡
│ Philadelphia ┆ Spring ┆ Sunny │
│ Philadelphia ┆ Summer ┆ Sunny │
│ Philadelphia ┆ Autumn ┆ Sunny │
│ Philadelphia ┆ Winter ┆ Sunny │
└──────────────┴────────┴─────────┘
"""
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
value_pyexpr = parse_into_expression(value, str_as_lit=True)
return wrap_expr(
self._pyexpr.str_replace_n(pattern_pyexpr, value_pyexpr, literal, n)
)
def replace_all(
self, pattern: str | Expr, value: str | Expr, *, literal: bool = False
) -> Expr:
r"""
Replace all matching regex/literal substrings with a new string value.
Parameters
----------
pattern
A valid regular expression pattern, compatible with the `regex crate
<https://docs.rs/regex/latest/regex/>`_.
value
String that will replace the matched substring.
literal
Treat `pattern` as a literal string, not a regex.
See Also
--------
replace
Notes
-----
* To modify regular expression behaviour (such as case-sensitivity) with flags,
use the inline `(?iLmsuxU)` syntax. See the regex crate's section on
`grouping and flags <https://docs.rs/regex/latest/regex/#grouping-and-flags>`_
for additional information about the use of inline expression modifiers.
* The dollar sign (`$`) is a special character related to capture groups; if you
want to replace some target pattern with characters that include a literal `$`
you should escape it by doubling it up as `$$`, or set `literal=True` if you
do not need a full regular expression pattern match. Otherwise, you will be
referencing a (potentially non-existent) capture group.
In the example below we need to double up `$` to represent a literal dollar
sign, otherwise we are referring to a capture group (which may or may not
exist):
.. code-block:: python
>>> df = pl.DataFrame({"text": ["ab12cd34ef", "gh45ij67kl"]})
>>> df.with_columns(
... # the replacement pattern refers back to the capture group
... text1=pl.col("text").str.replace_all(r"(?<N>\d{2,})", "$N$"),
... # doubling-up the `$` results in it appearing as a literal value
... text2=pl.col("text").str.replace_all(r"(?<N>\d{2,})", "$$N$$"),
... )
shape: (2, 3)
┌────────────┬──────────────┬──────────────┐
│ text ┆ text1 ┆ text2 │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞════════════╪══════════════╪══════════════╡
│ ab12cd34ef ┆ ab12$cd34$ef ┆ ab$N$cd$N$ef │
│ gh45ij67kl ┆ gh45$ij67$kl ┆ gh$N$ij$N$kl │
└────────────┴──────────────┴──────────────┘
Examples
--------
>>> df = pl.DataFrame({"id": [1, 2], "text": ["abcabc", "123a123"]})
>>> df.with_columns(pl.col("text").str.replace_all("a", "-"))
shape: (2, 2)
┌─────┬─────────┐
│ id ┆ text │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═════════╡
│ 1 ┆ -bc-bc │
│ 2 ┆ 123-123 │
└─────┴─────────┘
Capture groups are supported. Use `$1` or `${1}` in the `value` string to refer
to the first capture group in the `pattern`, `$2` or `${2}` to refer to the
second capture group, and so on. You can also use *named* capture groups.
>>> df = pl.DataFrame({"word": ["hat", "hut"]})
>>> df.with_columns(
... positional=pl.col.word.str.replace_all("h(.)t", "b${1}d"),
... named=pl.col.word.str.replace_all("h(?<vowel>.)t", "b${vowel}d"),
... )
shape: (2, 3)
┌──────┬────────────┬───────┐
│ word ┆ positional ┆ named │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════╪════════════╪═══════╡
│ hat ┆ bad ┆ bad │
│ hut ┆ bud ┆ bud │
└──────┴────────────┴───────┘
Apply case-insensitive string replacement using the `(?i)` flag.
>>> df = pl.DataFrame(
... {
... "city": "Philadelphia",
... "season": ["Spring", "Summer", "Autumn", "Winter"],
... "weather": ["Rainy", "Sunny", "Cloudy", "Snowy"],
... }
... )
>>> df.with_columns(
... # apply case-insensitive string replacement
... pl.col("weather").str.replace_all(
... r"(?i)foggy|rainy|cloudy|snowy", "Sunny"
... )
... )
shape: (4, 3)
┌──────────────┬────────┬─────────┐
│ city ┆ season ┆ weather │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════════════╪════════╪═════════╡
│ Philadelphia ┆ Spring ┆ Sunny │
│ Philadelphia ┆ Summer ┆ Sunny │
│ Philadelphia ┆ Autumn ┆ Sunny │
│ Philadelphia ┆ Winter ┆ Sunny │
└──────────────┴────────┴─────────┘
"""
pattern_pyexpr = parse_into_expression(pattern, str_as_lit=True)
value_pyexpr = parse_into_expression(value, str_as_lit=True)
return wrap_expr(
self._pyexpr.str_replace_all(pattern_pyexpr, value_pyexpr, literal)
)
def reverse(self) -> Expr:
"""
Returns string values in reversed order.
Examples
--------
>>> df = pl.DataFrame({"text": ["foo", "bar", "man\u0303ana"]})
>>> df.with_columns(pl.col("text").str.reverse().alias("reversed"))
shape: (3, 2)
┌────────┬──────────┐
│ text ┆ reversed │
│ --- ┆ --- │
│ str ┆ str │
╞════════╪══════════╡
│ foo ┆ oof │
│ bar ┆ rab │
│ mañana ┆ anañam │
└────────┴──────────┘
"""
return wrap_expr(self._pyexpr.str_reverse())
def slice(
self, offset: int | IntoExprColumn, length: int | IntoExprColumn | None = None
) -> Expr:
"""
Extract a substring from each string value.
Parameters
----------
offset
Start index. Negative indexing is supported.
length
Length of the slice. If set to `None` (default), the slice is taken to the
end of the string.
Returns
-------
Expr
Expression of data type :class:`String`.
Notes
-----
Both the `offset` and `length` inputs are defined in terms of the number
of characters in the (UTF8) string. A character is defined as a
`Unicode scalar value`_. A single character is represented by a single byte
when working with ASCII text, and a maximum of 4 bytes otherwise.
.. _Unicode scalar value: https://www.unicode.org/glossary/#unicode_scalar_value
Examples
--------
>>> df = pl.DataFrame(
... {
... "s": ["pear", None, "papaya", "dragonfruit"],
... "idx": [1, 3, 5, 7],
... }
... )
>>> df.select("s", substr=pl.col("s").str.slice(-3))
shape: (4, 2)
┌─────────────┬────────┐
│ s ┆ substr │
│ --- ┆ --- │
│ str ┆ str │
╞═════════════╪════════╡
│ pear ┆ ear │
│ null ┆ null │
│ papaya ┆ aya │
│ dragonfruit ┆ uit │
└─────────────┴────────┘
Using the optional `length` parameter and passing `offset` as an expression:
>>> df.with_columns(substr=pl.col("s").str.slice("idx", length=3))
shape: (4, 3)
┌─────────────┬─────┬────────┐
│ s ┆ idx ┆ substr │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str │
╞═════════════╪═════╪════════╡
│ pear ┆ 1 ┆ ear │
│ null ┆ 3 ┆ null │
│ papaya ┆ 5 ┆ a │
│ dragonfruit ┆ 7 ┆ rui │
└─────────────┴─────┴────────┘
"""
offset_pyexpr = parse_into_expression(offset)
length_pyexpr = parse_into_expression(length)
return wrap_expr(self._pyexpr.str_slice(offset_pyexpr, length_pyexpr))
def head(self, n: int | IntoExprColumn) -> Expr:
"""
Return the first n characters of each string in a String Series.
Parameters
----------
n
Length of the slice (integer or expression). Negative indexing is supported;
see note (2) below.
Returns
-------
Expr
Expression of data type :class:`String`.
Notes
-----
1) The `n` input is defined in terms of the number of characters in the (UTF8)
string. A character is defined as a `Unicode scalar value`_. A single
character is represented by a single byte when working with ASCII text, and a
maximum of 4 bytes otherwise.
.. _Unicode scalar value: https://www.unicode.org/glossary/#unicode_scalar_value
2) When the `n` input is negative, `head` returns characters up to the `n`th
from the end of the string. For example, if `n = -3`, then all characters
except the last three are returned.
3) If the length of the string has fewer than `n` characters, the full string is
returned.
Examples
--------
Return up to the first 5 characters:
>>> df = pl.DataFrame({"s": ["pear", None, "papaya", "dragonfruit"]})
>>> df.with_columns(pl.col("s").str.head(5).alias("s_head_5"))
shape: (4, 2)
┌─────────────┬──────────┐
│ s ┆ s_head_5 │
│ --- ┆ --- │
│ str ┆ str │
╞═════════════╪══════════╡
│ pear ┆ pear │
│ null ┆ null │
│ papaya ┆ papay │
│ dragonfruit ┆ drago │
└─────────────┴──────────┘
Return characters determined by column `n`:
>>> df = pl.DataFrame(
... {
... "s": ["pear", None, "papaya", "dragonfruit"],
... "n": [3, 4, -2, -5],
... }
... )
>>> df.with_columns(pl.col("s").str.head("n").alias("s_head_n"))
shape: (4, 3)
┌─────────────┬─────┬──────────┐
│ s ┆ n ┆ s_head_n │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str │
╞═════════════╪═════╪══════════╡
│ pear ┆ 3 ┆ pea │
│ null ┆ 4 ┆ null │
│ papaya ┆ -2 ┆ papa │
│ dragonfruit ┆ -5 ┆ dragon │
└─────────────┴─────┴──────────┘
"""
n_pyexpr = parse_into_expression(n)
return wrap_expr(self._pyexpr.str_head(n_pyexpr))
def tail(self, n: int | IntoExprColumn) -> Expr:
"""
Return the last n characters of each string in a String Series.
Parameters
----------
n
Length of the slice (integer or expression). Negative indexing is supported;
see note (2) below.
Returns
-------
Expr
Expression of data type :class:`String`.
Notes
-----
1) The `n` input is defined in terms of the number of characters in the (UTF8)
string. A character is defined as a `Unicode scalar value`_. A single
character is represented by a single byte when working with ASCII text, and a
maximum of 4 bytes otherwise.
.. _Unicode scalar value: https://www.unicode.org/glossary/#unicode_scalar_value
2) When the `n` input is negative, `tail` returns characters starting from the
`n`th from the beginning of the string. For example, if `n = -3`, then all
characters except the first three are returned.
3) If the length of the string has fewer than `n` characters, the full string is
returned.
Examples
--------
Return up to the last 5 characters:
>>> df = pl.DataFrame({"s": ["pear", None, "papaya", "dragonfruit"]})
>>> df.with_columns(pl.col("s").str.tail(5).alias("s_tail_5"))
shape: (4, 2)
┌─────────────┬──────────┐
│ s ┆ s_tail_5 │
│ --- ┆ --- │
│ str ┆ str │
╞═════════════╪══════════╡
│ pear ┆ pear │
│ null ┆ null │
│ papaya ┆ apaya │
│ dragonfruit ┆ fruit │
└─────────────┴──────────┘
Return characters determined by column `n`:
>>> df = pl.DataFrame(
... {
... "s": ["pear", None, "papaya", "dragonfruit"],
... "n": [3, 4, -2, -5],
... }
... )
>>> df.with_columns(pl.col("s").str.tail("n").alias("s_tail_n"))
shape: (4, 3)
┌─────────────┬─────┬──────────┐
│ s ┆ n ┆ s_tail_n │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str │
╞═════════════╪═════╪══════════╡
│ pear ┆ 3 ┆ ear │
│ null ┆ 4 ┆ null │
│ papaya ┆ -2 ┆ paya │
│ dragonfruit ┆ -5 ┆ nfruit │
└─────────────┴─────┴──────────┘
"""
n_pyexpr = parse_into_expression(n)
return wrap_expr(self._pyexpr.str_tail(n_pyexpr))
@deprecated(
'`str.explode` is deprecated; use `str.split("").explode()` instead.'
" Note that empty strings will result in null instead of being preserved."
" To get the exact same behavior, split first and then use a `pl.when...then...otherwise`"
" expression to handle the empty list before exploding."
)
def explode(self) -> Expr:
"""
Returns a column with a separate row for every string character.
.. deprecated:: 0.20.31
Use the `.str.split("").explode()` method instead. Note that empty strings
will result in null instead of being preserved. To get the exact same
behavior, split first and then use a `pl.when...then...otherwise`
expression to handle the empty list before exploding.
Returns
-------
Expr
Expression of data type :class:`String`.
Examples
--------
>>> df = pl.DataFrame({"a": ["foo", "bar"]})
>>> df.select(pl.col("a").str.explode()) # doctest: +SKIP
shape: (6, 1)
┌─────┐
│ a │
│ --- │
│ str │
╞═════╡
│ f │
│ o │
│ o │
│ b │
│ a │
│ r │
└─────┘
"""
split = self.split("")
return F.when(split.ne_missing([])).then(split).otherwise([""]).explode()
def to_integer(
self,
*,
base: int | IntoExprColumn = 10,
dtype: PolarsIntegerType = Int64,
strict: bool = True,
) -> Expr:
"""
Convert a String column into an Int64 column with base radix.
Parameters
----------
base
Positive integer or expression which is the base of the string
we are parsing.
Default: 10.
dtype
Integer data type to cast the result to.
Default: Int64.
strict
Bool, Default=True will raise any ParseError or overflow as ComputeError.
False silently convert to Null.
Returns
-------
Expr
Expression of data type :class:`Int64`.
Examples
--------
>>> df = pl.DataFrame({"bin": ["110", "101", "010", "invalid"]})
>>> df.with_columns(
... parsed=pl.col("bin").str.to_integer(
... base=2, dtype=pl.Int32, strict=False
... )
... )
shape: (4, 2)
┌─────────┬────────┐
│ bin ┆ parsed │
│ --- ┆ --- │
│ str ┆ i32 │
╞═════════╪════════╡
│ 110 ┆ 6 │
│ 101 ┆ 5 │
│ 010 ┆ 2 │
│ invalid ┆ null │
└─────────┴────────┘
>>> df = pl.DataFrame({"hex": ["fa1e", "ff00", "cafe", None]})
>>> df.with_columns(parsed=pl.col("hex").str.to_integer(base=16, strict=True))
shape: (4, 2)
┌──────┬────────┐
│ hex ┆ parsed │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪════════╡
│ fa1e ┆ 64030 │
│ ff00 ┆ 65280 │
│ cafe ┆ 51966 │
│ null ┆ null │
└──────┴────────┘
"""
base_pyexpr = parse_into_expression(base, str_as_lit=False)
return wrap_expr(self._pyexpr.str_to_integer(base_pyexpr, dtype, strict))
def contains_any(
self,
patterns: IntoExpr,
*,
ascii_case_insensitive: bool = False,
) -> Expr:
"""
Use the Aho-Corasick algorithm to find matches.
Determines if any of the patterns are contained in the string.
Parameters
----------
patterns
String patterns to search.
ascii_case_insensitive
Enable ASCII-aware case-insensitive matching.
When this option is enabled, searching will be performed without respect
to case for ASCII letters (a-z and A-Z) only.
Notes
-----
This method supports matching on string literals only, and does not support
regular expression matching.
Examples
--------
>>> _ = pl.Config.set_fmt_str_lengths(100)
>>> df = pl.DataFrame(
... {
... "lyrics": [
... "Everybody wants to rule the world",
... "Tell me what you want, what you really really want",
... "Can you feel the love tonight",
... ]
... }
... )
>>> df.with_columns(
... pl.col("lyrics").str.contains_any(["you", "me"]).alias("contains_any")
... )
shape: (3, 2)
┌────────────────────────────────────────────────────┬──────────────┐
│ lyrics ┆ contains_any │
│ --- ┆ --- │
│ str ┆ bool │
╞════════════════════════════════════════════════════╪══════════════╡
│ Everybody wants to rule the world ┆ false │
│ Tell me what you want, what you really really want ┆ true │
│ Can you feel the love tonight ┆ true │
└────────────────────────────────────────────────────┴──────────────┘
"""
patterns_pyexpr = parse_into_expression(patterns, str_as_lit=False)
return wrap_expr(
self._pyexpr.str_contains_any(patterns_pyexpr, ascii_case_insensitive)
)
def replace_many(
self,
patterns: IntoExpr | Mapping[str, str],
replace_with: IntoExpr | NoDefault = no_default,
*,
ascii_case_insensitive: bool = False,
leftmost: bool = False,
) -> Expr:
"""
Use the Aho-Corasick algorithm to replace many matches.
Parameters
----------
patterns
String patterns to search and replace.
Accepts expression input. Strings are parsed as column names, and other
non-expression inputs are parsed as literals. Also accepts a mapping of
patterns to their replacement as syntactic sugar for
`replace_many(pl.Series(mapping.keys()), pl.Series(mapping.values()))`.
replace_with
Strings to replace where a pattern was a match.
Accepts expression input. Non-expression inputs are parsed as literals.
Length must match the length of `patterns` or have length 1. This can be
broadcasted, so it supports many:one and many:many.
ascii_case_insensitive
Enable ASCII-aware case-insensitive matching.
When this option is enabled, searching will be performed without respect
to case for ASCII letters (a-z and A-Z) only.
leftmost
Guarantees in case there are overlapping matches that the leftmost match
is used. In case there are multiple candidates for the leftmost match
the pattern which comes first in patterns is used.
Notes
-----
This method supports matching on string literals only, and does not support
regular expression matching.
Examples
--------
Replace many patterns by passing sequences of equal length to the `patterns` and
`replace_with` parameters.
>>> _ = pl.Config.set_fmt_str_lengths(100)
>>> _ = pl.Config.set_tbl_width_chars(110)
>>> df = pl.DataFrame(
... {
... "lyrics": [
... "Everybody wants to rule the world",
... "Tell me what you want, what you really really want",
... "Can you feel the love tonight",
... ]
... }
... )
>>> df.with_columns(
... pl.col("lyrics")
... .str.replace_many(
... ["me", "you"],
... ["you", "me"],
... )
... .alias("confusing")
... )
shape: (3, 2)
┌────────────────────────────────────────────────────┬───────────────────────────────────────────────────┐
│ lyrics ┆ confusing │
│ --- ┆ --- │
│ str ┆ str │
╞════════════════════════════════════════════════════╪═══════════════════════════════════════════════════╡
│ Everybody wants to rule the world ┆ Everybody wants to rule the world │
│ Tell me what you want, what you really really want ┆ Tell you what me want, what me really really want │
│ Can you feel the love tonight ┆ Can me feel the love tonight │
└────────────────────────────────────────────────────┴───────────────────────────────────────────────────┘
Broadcast a replacement for many patterns by passing sequence of length 1 to the
`replace_with` parameter.
>>> _ = pl.Config.set_fmt_str_lengths(100)
>>> df = pl.DataFrame(
... {
... "lyrics": [
... "Everybody wants to rule the world",
... "Tell me what you want, what you really really want",
... "Can you feel the love tonight",
... ]
... }
... )
>>> df.with_columns(
... pl.col("lyrics")
... .str.replace_many(
... ["me", "you", "they"],
... [""],
... )
... .alias("removes_pronouns")
... )
shape: (3, 2)
┌────────────────────────────────────────────────────┬────────────────────────────────────────────┐
│ lyrics ┆ removes_pronouns │
│ --- ┆ --- │
│ str ┆ str │
╞════════════════════════════════════════════════════╪════════════════════════════════════════════╡
│ Everybody wants to rule the world ┆ Everybody wants to rule the world │
│ Tell me what you want, what you really really want ┆ Tell what want, what really really want │
│ Can you feel the love tonight ┆ Can feel the love tonight │
└────────────────────────────────────────────────────┴────────────────────────────────────────────┘
Passing a mapping with patterns and replacements is also supported as syntactic
sugar.
>>> _ = pl.Config.set_fmt_str_lengths(100)
>>> _ = pl.Config.set_tbl_width_chars(110)
>>> df = pl.DataFrame(
... {
... "lyrics": [
... "Everybody wants to rule the world",
... "Tell me what you want, what you really really want",
... "Can you feel the love tonight",
... ]
... }
... )
>>> mapping = {"me": "you", "you": "me", "want": "need"}
>>> df.with_columns(
... pl.col("lyrics").str.replace_many(mapping).alias("confusing")
... )
shape: (3, 2)
┌────────────────────────────────────────────────────┬───────────────────────────────────────────────────┐
│ lyrics ┆ confusing │
│ --- ┆ --- │
│ str ┆ str │
╞════════════════════════════════════════════════════╪═══════════════════════════════════════════════════╡
│ Everybody wants to rule the world ┆ Everybody needs to rule the world │
│ Tell me what you want, what you really really want ┆ Tell you what me need, what me really really need │
│ Can you feel the love tonight ┆ Can me feel the love tonight │
└────────────────────────────────────────────────────┴───────────────────────────────────────────────────┘
Using `leftmost` and changing order of tokens in `patterns`, you can get fine control over replacement
logic, while default behavior does not provide guarantees in case of overlapping patterns:
>>> df = pl.DataFrame({"haystack": ["abcd"]})
>>> patterns = {"b": "x", "abc": "y", "abcd": "z"}
>>> df.with_columns(replaced=pl.col("haystack").str.replace_many(patterns))
shape: (1, 2)
┌──────────┬──────────┐
│ haystack ┆ replaced │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪══════════╡
│ abcd ┆ axcd │
└──────────┴──────────┘
Note that here `replaced` can be any of `axcd`, `yd` or `z`.
Adding `leftmost=True` matches pattern with leftmost start index first:
>>> df = pl.DataFrame({"haystack": ["abcd"]})
>>> patterns = {"b": "x", "abc": "y", "abcd": "z"}
>>> df.with_columns(
... replaced=pl.col("haystack").str.replace_many(patterns, leftmost=True)
... )
shape: (1, 2)
┌──────────┬──────────┐
│ haystack ┆ replaced │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪══════════╡
│ abcd ┆ yd │
└──────────┴──────────┘
Changing order inside patterns to match 'abcd' first:
>>> df = pl.DataFrame({"haystack": ["abcd"]})
>>> patterns = {"abcd": "z", "abc": "y", "b": "x"}
>>> df.with_columns(
... replaced=pl.col("haystack").str.replace_many(patterns, leftmost=True)
... )
shape: (1, 2)
┌──────────┬──────────┐
│ haystack ┆ replaced │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪══════════╡
│ abcd ┆ z │
└──────────┴──────────┘
""" # noqa: W505
if replace_with is no_default:
if not isinstance(patterns, Mapping):
msg = "`replace_with` argument is required if `patterns` argument is not a Mapping type"
raise TypeError(msg)
# Early return in case of an empty mapping.
if not patterns:
return wrap_expr(self._pyexpr)
replace_with = list(patterns.values())
patterns = list(patterns.keys())
patterns_pyexpr = parse_into_expression(
patterns, # type: ignore[arg-type]
str_as_lit=False,
)
replace_with_pyexpr = parse_into_expression(replace_with, str_as_lit=True)
return wrap_expr(
self._pyexpr.str_replace_many(
patterns_pyexpr, replace_with_pyexpr, ascii_case_insensitive, leftmost
)
)
@unstable()
def extract_many(
self,
patterns: IntoExpr,
*,
ascii_case_insensitive: bool = False,
overlapping: bool = False,
leftmost: bool = False,
) -> Expr:
"""
Use the Aho-Corasick algorithm to extract many matches.
Parameters
----------
patterns
String patterns to search.
ascii_case_insensitive
Enable ASCII-aware case-insensitive matching.
When this option is enabled, searching will be performed without respect
to case for ASCII letters (a-z and A-Z) only.
overlapping
Whether matches may overlap.
leftmost
Guarantees in case there are overlapping matches that the leftmost match
is used. In case there are multiple candidates for the leftmost match
the pattern which comes first in patterns is used. May not be used
together with overlapping = True.
Notes
-----
This method supports matching on string literals only, and does not support
regular expression matching.
Examples
--------
>>> _ = pl.Config.set_fmt_str_lengths(100)
>>> df = pl.DataFrame({"values": ["discontent"]})
>>> patterns = ["winter", "disco", "onte", "discontent"]
>>> df.with_columns(
... pl.col("values")
... .str.extract_many(patterns, overlapping=False)
... .alias("matches"),
... pl.col("values")
... .str.extract_many(patterns, overlapping=True)
... .alias("matches_overlapping"),
... )
shape: (1, 3)
┌────────────┬───────────┬─────────────────────────────────┐
│ values ┆ matches ┆ matches_overlapping │
│ --- ┆ --- ┆ --- │
│ str ┆ list[str] ┆ list[str] │
╞════════════╪═══════════╪═════════════════════════════════╡
│ discontent ┆ ["disco"] ┆ ["disco", "onte", "discontent"] │
└────────────┴───────────┴─────────────────────────────────┘
>>> df = pl.DataFrame(
... {
... "values": ["discontent", "rhapsody"],
... "patterns": [
... ["winter", "disco", "onte", "discontent"],
... ["rhap", "ody", "coalesce"],
... ],
... }
... )
>>> df.select(pl.col("values").str.extract_many("patterns"))
shape: (2, 1)
┌─────────────────┐
│ values │
│ --- │
│ list[str] │
╞═════════════════╡
│ ["disco"] │
│ ["rhap", "ody"] │
└─────────────────┘
See Also
--------
replace_many
"""
if overlapping and leftmost:
msg = "can not match overlapping patterns when leftmost == True"
raise ValueError(msg)
patterns_pyexpr = parse_into_expression(patterns, str_as_lit=False)
return wrap_expr(
self._pyexpr.str_extract_many(
patterns_pyexpr, ascii_case_insensitive, overlapping, leftmost
)
)
@unstable()
def find_many(
self,
patterns: IntoExpr,
*,
ascii_case_insensitive: bool = False,
overlapping: bool = False,
leftmost: bool = False,
) -> Expr:
"""
Use the Aho-Corasick algorithm to find many matches.
The function will return the bytes offset of the start of each match.
The return type will be `List<UInt32>`
Parameters
----------
patterns
String patterns to search.
ascii_case_insensitive
Enable ASCII-aware case-insensitive matching.
When this option is enabled, searching will be performed without respect
to case for ASCII letters (a-z and A-Z) only.
overlapping
Whether matches may overlap.
leftmost
Guarantees in case there are overlapping matches that the leftmost match
is used. In case there are multiple candidates for the leftmost match
the pattern which comes first in patterns is used. May not be used
together with overlapping = True.
Notes
-----
This method supports matching on string literals only, and does not support
regular expression matching.
Examples
--------
>>> _ = pl.Config.set_fmt_str_lengths(100)
>>> df = pl.DataFrame({"values": ["discontent"]})
>>> patterns = ["winter", "disco", "onte", "discontent"]
>>> df.with_columns(
... pl.col("values")
... .str.find_many(patterns, overlapping=False)
... .alias("matches"),
... pl.col("values")
... .str.find_many(patterns, overlapping=True)
... .alias("matches_overlapping"),
... )
shape: (1, 3)
┌────────────┬───────────┬─────────────────────┐
│ values ┆ matches ┆ matches_overlapping │
│ --- ┆ --- ┆ --- │
│ str ┆ list[u32] ┆ list[u32] │
╞════════════╪═══════════╪═════════════════════╡
│ discontent ┆ [0] ┆ [0, 4, 0] │
└────────────┴───────────┴─────────────────────┘
>>> df = pl.DataFrame(
... {
... "values": ["discontent", "rhapsody"],
... "patterns": [
... ["winter", "disco", "onte", "discontent"],
... ["rhap", "ody", "coalesce"],
... ],
... }
... )
>>> df.select(pl.col("values").str.find_many("patterns"))
shape: (2, 1)
┌───────────┐
│ values │
│ --- │
│ list[u32] │
╞═══════════╡
│ [0] │
│ [0, 5] │
└───────────┘
See Also
--------
replace_many
"""
if overlapping and leftmost:
msg = "can not match overlapping patterns when leftmost == True"
raise ValueError(msg)
patterns_pyexpr = parse_into_expression(patterns, str_as_lit=False)
return wrap_expr(
self._pyexpr.str_find_many(
patterns_pyexpr, ascii_case_insensitive, overlapping, leftmost
)
)
def join(self, delimiter: str = "", *, ignore_nulls: bool = True) -> Expr:
"""
Vertically concatenate the string values in the column to a single string value.
Parameters
----------
delimiter
The delimiter to insert between consecutive string values.
ignore_nulls
Ignore null values (default).
If set to `False`, null values will be propagated. This means that
if the column contains any null values, the output is null.
Returns
-------
Expr
Expression of data type :class:`String`.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, None, 3]})
>>> df.select(pl.col("foo").str.join("-"))
shape: (1, 1)
┌─────┐
│ foo │
│ --- │
│ str │
╞═════╡
│ 1-3 │
└─────┘
>>> df.select(pl.col("foo").str.join(ignore_nulls=False))
shape: (1, 1)
┌──────┐
│ foo │
│ --- │
│ str │
╞══════╡
│ null │
└──────┘
"""
return wrap_expr(self._pyexpr.str_join(delimiter, ignore_nulls=ignore_nulls))
@deprecated(
"`str.concat` is deprecated; use `str.join` instead. Note also that the "
"default `delimiter` for `str.join` is an empty string, not a hyphen."
)
def concat(
self, delimiter: str | None = None, *, ignore_nulls: bool = True
) -> Expr:
"""
Vertically concatenate the string values in the column to a single string value.
.. deprecated:: 1.0.0
Use :meth:`join` instead. Note that the default `delimiter` for :meth:`join`
is an empty string instead of a hyphen.
Parameters
----------
delimiter
The delimiter to insert between consecutive string values.
ignore_nulls
Ignore null values (default).
If set to `False`, null values will be propagated. This means that
if the column contains any null values, the output is null.
Returns
-------
Expr
Expression of data type :class:`String`.
Examples
--------
>>> df = pl.DataFrame({"foo": [1, None, 2]})
>>> df.select(pl.col("foo").str.concat("-")) # doctest: +SKIP
shape: (1, 1)
┌─────┐
│ foo │
│ --- │
│ str │
╞═════╡
│ 1-2 │
└─────┘
>>> df.select(
... pl.col("foo").str.concat("-", ignore_nulls=False)
... ) # doctest: +SKIP
shape: (1, 1)
┌──────┐
│ foo │
│ --- │
│ str │
╞══════╡
│ null │
└──────┘
"""
if delimiter is None:
delimiter = "-"
return self.join(delimiter, ignore_nulls=ignore_nulls)
def escape_regex(self) -> Expr:
r"""
Returns string values with all regular expression meta characters escaped.
Examples
--------
>>> df = pl.DataFrame({"text": ["abc", "def", None, "abc(\\w+)"]})
>>> df.with_columns(pl.col("text").str.escape_regex().alias("escaped"))
shape: (4, 2)
┌──────────┬──────────────┐
│ text ┆ escaped │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪══════════════╡
│ abc ┆ abc │
│ def ┆ def │
│ null ┆ null │
│ abc(\w+) ┆ abc\(\\w\+\) │
└──────────┴──────────────┘
"""
return wrap_expr(self._pyexpr.str_escape_regex())
def normalize(self, form: UnicodeForm = "NFC") -> Expr:
"""
Returns the Unicode normal form of the string values.
This uses the forms described in Unicode Standard Annex 15: <https://www.unicode.org/reports/tr15/>.
Parameters
----------
form : {'NFC', 'NFKC', 'NFD', 'NFKD'}
Unicode form to use.
Examples
--------
>>> df = pl.DataFrame({"text": ["01²", "KADOKAWA"]})
>>> new = df.with_columns(
... nfc=pl.col("text").str.normalize("NFC"),
... nfkc=pl.col("text").str.normalize("NFKC"),
... )
>>> new
shape: (2, 3)
┌──────────────────┬──────────────────┬──────────┐
│ text ┆ nfc ┆ nfkc │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════════════════╪══════════════════╪══════════╡
│ 01² ┆ 01² ┆ 012 │
│ KADOKAWA ┆ KADOKAWA ┆ KADOKAWA │
└──────────────────┴──────────────────┴──────────┘
>>> new.select(pl.all().str.len_bytes())
shape: (2, 3)
┌──────┬─────┬──────┐
│ text ┆ nfc ┆ nfkc │
│ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ u32 │
╞══════╪═════╪══════╡
│ 4 ┆ 4 ┆ 3 │
│ 24 ┆ 24 ┆ 8 │
└──────┴─────┴──────┘
""" # noqa: RUF002
return wrap_expr(self._pyexpr.str_normalize(form))
def _validate_format_argument(format: str | None) -> None:
if format is not None and ".%f" in format:
message = (
"Detected the pattern `.%f` in the chrono format string."
" This pattern should not be used to parse values after a decimal point."
" Use `%.f` instead."
" See the full specification: https://docs.rs/chrono/latest/chrono/format/strftime"
)
warnings.warn(message, ChronoFormatWarning, stacklevel=find_stacklevel())
|
ExprStringNameSpace
|
python
|
celery__celery
|
t/smoke/tests/test_canvas.py
|
{
"start": 541,
"end": 945
}
|
class ____:
def test_sanity(self, celery_setup: CeleryTestSetup):
sig = group(
group(add.si(1, 1), add.si(2, 2)),
group([add.si(1, 1), add.si(2, 2)]),
group(s for s in [add.si(1, 1), add.si(2, 2)]),
)
res = sig.apply_async(queue=celery_setup.worker.worker_queue)
assert res.get(timeout=RESULT_TIMEOUT) == [2, 4, 2, 4, 2, 4]
|
test_group
|
python
|
great-expectations__great_expectations
|
great_expectations/datasource/fluent/pandas_datasource.py
|
{
"start": 2508,
"end": 13193
}
|
class ____(DataAsset):
"""
A Pandas DataAsset is a DataAsset that is backed by a Pandas DataFrame.
"""
_EXCLUDE_FROM_READER_OPTIONS: ClassVar[Set[str]] = {
"batch_definitions",
"batch_metadata",
"name",
"order_by",
"type",
"id",
}
class Config:
"""
Need to allow extra fields for the base type because pydantic will first create
an instance of `_PandasDataAsset` before we select and create the more specific
asset subtype.
Each specific subtype should `forbid` extra fields.
"""
extra = pydantic.Extra.allow
def _get_reader_method(self) -> str:
raise NotImplementedError(
"""One needs to explicitly provide "reader_method" for Pandas DataAsset extensions as temporary \
work-around, until "type" naming convention and method for obtaining 'reader_method' from it are established.""" # noqa: E501 # FIXME CoP
)
@override
def test_connection(self) -> None: ...
@override
def get_batch_parameters_keys(
self, partitioner: Optional[ColumnPartitioner] = None
) -> Tuple[str, ...]:
return tuple(
"dataframe",
)
@override
def get_batch_identifiers_list(self, batch_request: BatchRequest) -> List[dict]:
return [IDDict(batch_request.options)]
@override
def get_batch(self, batch_request: BatchRequest) -> Batch:
self._validate_batch_request(batch_request)
batch_spec = PandasBatchSpec(
reader_method=self._get_reader_method(),
reader_options=self.dict(
exclude=self._EXCLUDE_FROM_READER_OPTIONS,
exclude_unset=True,
by_alias=True,
config_provider=self._datasource._config_provider,
),
)
execution_engine: PandasExecutionEngine = self.datasource.get_execution_engine()
data, markers = execution_engine.get_batch_data_and_markers(batch_spec=batch_spec)
# batch_definition (along with batch_spec and markers) is only here to satisfy a
# legacy constraint when computing usage statistics in a validator. We hope to remove
# it in the future.
batch_definition = LegacyBatchDefinition(
datasource_name=self.datasource.name,
data_connector_name=_DATA_CONNECTOR_NAME,
data_asset_name=self.name,
batch_identifiers=make_batch_identifier(batch_request.options),
batch_spec_passthrough=None,
)
batch_metadata: BatchMetadata = self._get_batch_metadata_from_batch_request(
batch_request=batch_request, ignore_options=("dataframe",)
)
return Batch(
datasource=self.datasource,
data_asset=self,
batch_request=batch_request,
data=data,
metadata=batch_metadata,
batch_markers=markers,
batch_spec=batch_spec,
batch_definition=batch_definition,
)
@override
def build_batch_request(
self,
options: Optional[BatchParameters] = None,
batch_slice: Optional[BatchSlice] = None,
partitioner: Optional[ColumnPartitioner] = None,
) -> BatchRequest:
"""A batch request that can be used to obtain batches for this DataAsset.
Args:
options: This is not currently supported and must be {}/None for this data asset.
batch_slice: This is not currently supported and must be None for this data asset.
partitioner: This is not currently supported and must be None for this data asset.
Returns:
A BatchRequest object that can be used to obtain a batch from an Asset by calling the
get_batch method.
"""
if options:
raise BuildBatchRequestError(
message="options is not currently supported for this DataAsset "
"and must be None or {}."
)
if batch_slice is not None:
raise BuildBatchRequestError(
message="batch_slice is not currently supported for this DataAsset "
"and must be None."
)
if partitioner is not None:
raise BuildBatchRequestError(
message="partitioner is not currently supported for this DataAsset "
"and must be None."
)
return BatchRequest(
datasource_name=self.datasource.name,
data_asset_name=self.name,
options={},
)
@public_api
def add_batch_definition_whole_dataframe(self, name: str) -> BatchDefinition:
"""
Add a BatchDefinition that requests the whole dataframe.
Args:
name: The name of the BatchDefinition.
Returns:
A BatchDefinition with no partitioning.
"""
return self.add_batch_definition(
name=name,
partitioner=None,
)
@override
def _validate_batch_request(self, batch_request: BatchRequest) -> None:
"""Validates the batch_request has the correct form.
Args:
batch_request: A batch request object to be validated.
"""
if not (
batch_request.datasource_name == self.datasource.name
and batch_request.data_asset_name == self.name
and not batch_request.options
):
expect_batch_request_form = BatchRequest[None](
datasource_name=self.datasource.name,
data_asset_name=self.name,
options={},
batch_slice=batch_request._batch_slice_input,
)
raise gx_exceptions.InvalidBatchRequestError( # noqa: TRY003 # FIXME CoP
"BatchRequest should have form:\n"
f"{pf(expect_batch_request_form.dict())}\n"
f"but actually has form:\n{pf(batch_request.dict())}\n"
)
@override
def json( # noqa: PLR0913 # FIXME CoP
self,
*,
include: AbstractSetIntStr | MappingIntStrAny | None = None,
exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
by_alias: bool = False,
# deprecated - use exclude_unset instead
skip_defaults: bool | None = None,
# Default to True to prevent serializing long configs full of unset default values
exclude_unset: bool = True,
exclude_defaults: bool = False,
exclude_none: bool = False,
encoder: Callable[[Any], Any] | None = None,
models_as_dict: bool = True,
**dumps_kwargs: Any,
) -> str:
"""
Generate a JSON representation of the model, `include` and `exclude` arguments
as per `dict()`.
`encoder` is an optional function to supply as `default` to json.dumps(), other
arguments as per `json.dumps()`.
Deviates from pydantic `exclude_unset` `True` by default instead of `False` by
default.
"""
exclude_fields: dict[int | str, Any] = self._include_exclude_to_dict(
include_exclude=exclude
)
# don't check fields that should always be set
check_fields: set[str] = self.__fields_set__.copy().difference(_FIELDS_ALWAYS_SET)
for field in check_fields:
if isinstance(getattr(self, field), tuple(_EXCLUDE_TYPES_FROM_JSON)):
exclude_fields[field] = True
return super().json(
include=include,
exclude=exclude_fields,
by_alias=by_alias,
skip_defaults=skip_defaults,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
encoder=encoder,
models_as_dict=models_as_dict,
**dumps_kwargs,
)
_PANDAS_READER_METHOD_UNSUPPORTED_LIST: tuple[str, ...] = (
# "read_csv",
# "read_json",
# "read_excel",
# "read_parquet",
# "read_clipboard",
# "read_feather",
# "read_fwf",
# "read_gbq",
# "read_hdf",
# "read_html",
# "read_orc",
# "read_pickle",
# "read_sas",
# "read_spss",
# "read_sql",
# "read_sql_query",
# "read_sql_table",
# "read_stata",
# "read_table",
# "read_xml",
)
_PANDAS_ASSET_MODELS = _generate_pandas_data_asset_models(
_PandasDataAsset,
blacklist=_PANDAS_READER_METHOD_UNSUPPORTED_LIST,
use_docstring_from_method=True,
skip_first_param=False,
)
ClipboardAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("clipboard", _PandasDataAsset)
CSVAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("csv", _PandasDataAsset)
ExcelAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("excel", _PandasDataAsset)
FeatherAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("feather", _PandasDataAsset)
FWFAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("fwf", _PandasDataAsset)
GBQAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("gbq", _PandasDataAsset)
HDFAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("hdf", _PandasDataAsset)
HTMLAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("html", _PandasDataAsset)
JSONAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("json", _PandasDataAsset)
ORCAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("orc", _PandasDataAsset)
ParquetAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("parquet", _PandasDataAsset)
PickleAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("pickle", _PandasDataAsset)
SQLAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("sql", _PandasDataAsset)
SQLQueryAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("sql_query", _PandasDataAsset)
SQLTableAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("sql_table", _PandasDataAsset)
SASAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("sas", _PandasDataAsset)
SPSSAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("spss", _PandasDataAsset)
StataAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("stata", _PandasDataAsset)
TableAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get("table", _PandasDataAsset)
XMLAsset: Type[_PandasDataAsset] = _PANDAS_ASSET_MODELS.get(
"xml", _PandasDataAsset
) # read_xml doesn't exist for pandas < 1.3
def _short_id() -> str:
"""
Generate a unique id by shortening a uuid4.
Can expect collision after several million iterations.
https://gist.github.com/Kilo59/82f227d9dba4e5cce62bc22b245b2638
"""
return str(uuid.uuid4()).replace("-", "")[:11]
|
_PandasDataAsset
|
python
|
pandas-dev__pandas
|
pandas/tests/extension/base/methods.py
|
{
"start": 354,
"end": 27303
}
|
class ____:
"""Various Series and DataFrame methods."""
def test_hash_pandas_object(self, data):
# _hash_pandas_object should return a uint64 ndarray of the same length
# as the data
from pandas.core.util.hashing import _default_hash_key
res = data._hash_pandas_object(
encoding="utf-8", hash_key=_default_hash_key, categorize=False
)
assert res.dtype == np.uint64
assert res.shape == data.shape
def test_value_counts_default_dropna(self, data):
# make sure we have consistent default dropna kwarg
if not hasattr(data, "value_counts"):
pytest.skip(f"value_counts is not implemented for {type(data)}")
sig = inspect.signature(data.value_counts)
kwarg = sig.parameters["dropna"]
assert kwarg.default is True
@pytest.mark.parametrize("dropna", [True, False])
def test_value_counts(self, all_data, dropna):
if dropna:
other = all_data[~all_data.isna()]
else:
other = all_data
result = pd.Series(all_data).value_counts(dropna=dropna).sort_index()
expected = pd.Series(other).value_counts(dropna=dropna).sort_index()
tm.assert_series_equal(result, expected)
def test_value_counts_with_normalize(self, data):
# GH 33172
data = data.unique()
values = np.array(data[~data.isna()])
ser = pd.Series(data, dtype=data.dtype)
result = ser.value_counts(normalize=True).sort_index()
if not isinstance(data, pd.Categorical):
expected = pd.Series(
[1 / len(values)] * len(values), index=result.index, name="proportion"
)
else:
expected = pd.Series(0.0, index=result.index, name="proportion")
expected[result > 0] = 1 / len(values)
if isinstance(data.dtype, pd.StringDtype) and data.dtype.na_value is np.nan:
# TODO: avoid special-casing
expected = expected.astype("float64")
elif getattr(data.dtype, "storage", "") == "pyarrow" or isinstance(
data.dtype, pd.ArrowDtype
):
# TODO: avoid special-casing
expected = expected.astype("double[pyarrow]")
elif na_value_for_dtype(data.dtype) is pd.NA:
# TODO(GH#44692): avoid special-casing
expected = expected.astype("Float64")
tm.assert_series_equal(result, expected)
def test_count(self, data_missing):
df = pd.DataFrame({"A": data_missing})
result = df.count(axis="columns")
expected = pd.Series([0, 1])
tm.assert_series_equal(result, expected)
def test_series_count(self, data_missing):
# GH#26835
ser = pd.Series(data_missing)
result = ser.count()
expected = 1
assert result == expected
def test_apply_simple_series(self, data):
result = pd.Series(data).apply(id)
assert isinstance(result, pd.Series)
@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data_missing, na_action):
result = data_missing.map(lambda x: x, na_action=na_action)
expected = data_missing.to_numpy()
tm.assert_numpy_array_equal(result, expected)
def test_argsort(self, data_for_sorting):
result = pd.Series(data_for_sorting).argsort()
# argsort result gets passed to take, so should be np.intp
expected = pd.Series(np.array([2, 0, 1], dtype=np.intp))
tm.assert_series_equal(result, expected)
def test_argsort_missing_array(self, data_missing_for_sorting):
result = data_missing_for_sorting.argsort()
# argsort result gets passed to take, so should be np.intp
expected = np.array([2, 0, 1], dtype=np.intp)
tm.assert_numpy_array_equal(result, expected)
def test_argsort_missing(self, data_missing_for_sorting):
result = pd.Series(data_missing_for_sorting).argsort()
expected = pd.Series(np.array([2, 0, 1], dtype=np.intp))
tm.assert_series_equal(result, expected)
def test_argmin_argmax(self, data_for_sorting, data_missing_for_sorting, na_value):
# GH 24382
is_bool = data_for_sorting.dtype._is_boolean
exp_argmax = 1
exp_argmax_repeated = 3
if is_bool:
# See data_for_sorting docstring
exp_argmax = 0
exp_argmax_repeated = 1
# data_for_sorting -> [B, C, A] with A < B < C
assert data_for_sorting.argmax() == exp_argmax
assert data_for_sorting.argmin() == 2
# with repeated values -> first occurrence
data = data_for_sorting.take([2, 0, 0, 1, 1, 2])
assert data.argmax() == exp_argmax_repeated
assert data.argmin() == 0
# with missing values
# data_missing_for_sorting -> [B, NA, A] with A < B and NA missing.
assert data_missing_for_sorting.argmax() == 0
assert data_missing_for_sorting.argmin() == 2
@pytest.mark.parametrize("method", ["argmax", "argmin"])
def test_argmin_argmax_empty_array(self, method, data):
# GH 24382
err_msg = "attempt to get"
with pytest.raises(ValueError, match=err_msg):
getattr(data[:0], method)()
@pytest.mark.parametrize("method", ["argmax", "argmin"])
def test_argmin_argmax_all_na(self, method, data, na_value):
# all missing with skipna=True is the same as empty
err_msg = "attempt to get"
data_na = type(data)._from_sequence([na_value, na_value], dtype=data.dtype)
with pytest.raises(ValueError, match=err_msg):
getattr(data_na, method)()
@pytest.mark.parametrize(
"op_name, skipna, expected",
[
("idxmax", True, 0),
("idxmin", True, 2),
("argmax", True, 0),
("argmin", True, 2),
("idxmax", False, -1),
("idxmin", False, -1),
("argmax", False, -1),
("argmin", False, -1),
],
)
def test_argreduce_series(
self, data_missing_for_sorting, op_name, skipna, expected
):
# data_missing_for_sorting -> [B, NA, A] with A < B and NA missing.
ser = pd.Series(data_missing_for_sorting)
if expected == -1:
with pytest.raises(ValueError, match="Encountered an NA value"):
getattr(ser, op_name)(skipna=skipna)
else:
result = getattr(ser, op_name)(skipna=skipna)
tm.assert_almost_equal(result, expected)
def test_argmax_argmin_no_skipna_notimplemented(self, data_missing_for_sorting):
# GH#38733
data = data_missing_for_sorting
with pytest.raises(ValueError, match="Encountered an NA value"):
data.argmin(skipna=False)
with pytest.raises(ValueError, match="Encountered an NA value"):
data.argmax(skipna=False)
@pytest.mark.parametrize(
"na_position, expected",
[
("last", np.array([2, 0, 1], dtype=np.dtype("intp"))),
("first", np.array([1, 2, 0], dtype=np.dtype("intp"))),
],
)
def test_nargsort(self, data_missing_for_sorting, na_position, expected):
# GH 25439
result = nargsort(data_missing_for_sorting, na_position=na_position)
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("ascending", [True, False])
def test_sort_values(self, data_for_sorting, ascending, sort_by_key):
ser = pd.Series(data_for_sorting)
result = ser.sort_values(ascending=ascending, key=sort_by_key)
expected = ser.iloc[[2, 0, 1]]
if not ascending:
# GH 35922. Expect stable sort
if ser.nunique() == 2:
expected = ser.iloc[[0, 1, 2]]
else:
expected = ser.iloc[[1, 0, 2]]
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("ascending", [True, False])
def test_sort_values_missing(
self, data_missing_for_sorting, ascending, sort_by_key
):
ser = pd.Series(data_missing_for_sorting)
result = ser.sort_values(ascending=ascending, key=sort_by_key)
if ascending:
expected = ser.iloc[[2, 0, 1]]
else:
expected = ser.iloc[[0, 2, 1]]
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("ascending", [True, False])
def test_sort_values_frame(self, data_for_sorting, ascending):
df = pd.DataFrame({"A": [1, 2, 1], "B": data_for_sorting})
result = df.sort_values(["A", "B"])
expected = pd.DataFrame(
{"A": [1, 1, 2], "B": data_for_sorting.take([2, 0, 1])}, index=[2, 0, 1]
)
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("keep", ["first", "last", False])
def test_duplicated(self, data, keep):
arr = data.take([0, 1, 0, 1])
result = arr.duplicated(keep=keep)
if keep == "first":
expected = np.array([False, False, True, True])
elif keep == "last":
expected = np.array([True, True, False, False])
else:
expected = np.array([True, True, True, True])
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("box", [pd.Series, lambda x: x])
@pytest.mark.parametrize("method", [lambda x: x.unique(), pd.unique])
def test_unique(self, data, box, method):
duplicated = box(data._from_sequence([data[0], data[0]], dtype=data.dtype))
result = method(duplicated)
assert len(result) == 1
assert isinstance(result, type(data))
assert result[0] == duplicated[0]
def test_factorize(self, data_for_grouping):
codes, uniques = pd.factorize(data_for_grouping, use_na_sentinel=True)
is_bool = data_for_grouping.dtype._is_boolean
if is_bool:
# only 2 unique values
expected_codes = np.array([0, 0, -1, -1, 1, 1, 0, 0], dtype=np.intp)
expected_uniques = data_for_grouping.take([0, 4])
else:
expected_codes = np.array([0, 0, -1, -1, 1, 1, 0, 2], dtype=np.intp)
expected_uniques = data_for_grouping.take([0, 4, 7])
tm.assert_numpy_array_equal(codes, expected_codes)
tm.assert_extension_array_equal(uniques, expected_uniques)
def test_factorize_equivalence(self, data_for_grouping):
codes_1, uniques_1 = pd.factorize(data_for_grouping, use_na_sentinel=True)
codes_2, uniques_2 = data_for_grouping.factorize(use_na_sentinel=True)
tm.assert_numpy_array_equal(codes_1, codes_2)
tm.assert_extension_array_equal(uniques_1, uniques_2)
assert len(uniques_1) == len(pd.unique(uniques_1))
assert uniques_1.dtype == data_for_grouping.dtype
def test_factorize_empty(self, data):
codes, uniques = pd.factorize(data[:0])
expected_codes = np.array([], dtype=np.intp)
expected_uniques = type(data)._from_sequence([], dtype=data[:0].dtype)
tm.assert_numpy_array_equal(codes, expected_codes)
tm.assert_extension_array_equal(uniques, expected_uniques)
def test_fillna_limit_frame(self, data_missing):
# GH#58001
df = pd.DataFrame({"A": data_missing.take([0, 1, 0, 1])})
expected = pd.DataFrame({"A": data_missing.take([1, 1, 0, 1])})
result = df.fillna(value=data_missing[1], limit=1)
tm.assert_frame_equal(result, expected)
def test_fillna_limit_series(self, data_missing):
# GH#58001
ser = pd.Series(data_missing.take([0, 1, 0, 1]))
expected = pd.Series(data_missing.take([1, 1, 0, 1]))
result = ser.fillna(value=data_missing[1], limit=1)
tm.assert_series_equal(result, expected)
def test_fillna_copy_frame(self, data_missing):
arr = data_missing.take([1, 1])
df = pd.DataFrame({"A": arr})
df_orig = df.copy()
filled_val = df.iloc[0, 0]
result = df.fillna(filled_val)
result.iloc[0, 0] = filled_val
tm.assert_frame_equal(df, df_orig)
def test_fillna_copy_series(self, data_missing):
arr = data_missing.take([1, 1])
ser = pd.Series(arr, copy=False)
ser_orig = ser.copy()
filled_val = ser[0]
result = ser.fillna(filled_val)
result.iloc[0] = filled_val
tm.assert_series_equal(ser, ser_orig)
def test_fillna_length_mismatch(self, data_missing):
msg = "Length of 'value' does not match."
with pytest.raises(ValueError, match=msg):
data_missing.fillna(data_missing.take([1]))
# Subclasses can override if we expect e.g Sparse[bool], boolean, pyarrow[bool]
_combine_le_expected_dtype: Dtype = NumpyEADtype("bool")
def test_combine_le(self, data_repeated):
# GH 20825
# Test that combine works when doing a <= (le) comparison
orig_data1, orig_data2 = data_repeated(2)
s1 = pd.Series(orig_data1)
s2 = pd.Series(orig_data2)
result = s1.combine(s2, lambda x1, x2: x1 <= x2)
expected = pd.Series(
pd.array(
[a <= b for (a, b) in zip(list(orig_data1), list(orig_data2))],
dtype=self._combine_le_expected_dtype,
)
)
tm.assert_series_equal(result, expected)
val = s1.iloc[0]
result = s1.combine(val, lambda x1, x2: x1 <= x2)
expected = pd.Series(
pd.array(
[a <= val for a in list(orig_data1)],
dtype=self._combine_le_expected_dtype,
)
)
tm.assert_series_equal(result, expected)
def _construct_for_combine_add(self, left, right):
if isinstance(right, type(left)):
return left._from_sequence(
[a + b for (a, b) in zip(list(left), list(right))],
dtype=left.dtype,
)
else:
return left._from_sequence(
[a + right for a in list(left)],
dtype=left.dtype,
)
def test_combine_add(self, data_repeated):
# GH 20825
orig_data1, orig_data2 = data_repeated(2)
s1 = pd.Series(orig_data1)
s2 = pd.Series(orig_data2)
# Check if the operation is supported pointwise for our scalars. If not,
# we will expect Series.combine to raise as well.
try:
with np.errstate(over="ignore"):
arr = self._construct_for_combine_add(orig_data1, orig_data2)
except TypeError:
# If the operation is not supported pointwise for our scalars,
# then Series.combine should also raise
with pytest.raises(TypeError):
s1.combine(s2, lambda x1, x2: x1 + x2)
return
expected = pd.Series(arr)
result = s1.combine(s2, lambda x1, x2: x1 + x2)
tm.assert_series_equal(result, expected)
val = s1.iloc[0]
result = s1.combine(val, lambda x1, x2: x1 + x2)
arr = self._construct_for_combine_add(orig_data1, val)
expected = pd.Series(arr)
tm.assert_series_equal(result, expected)
def test_combine_first(self, data):
# https://github.com/pandas-dev/pandas/issues/24147
a = pd.Series(data[:3])
b = pd.Series(data[2:5], index=[2, 3, 4])
result = a.combine_first(b)
expected = pd.Series(data[:5])
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("frame", [True, False])
@pytest.mark.parametrize(
"periods, indices",
[(-2, [2, 3, 4, -1, -1]), (0, [0, 1, 2, 3, 4]), (2, [-1, -1, 0, 1, 2])],
)
def test_container_shift(self, data, frame, periods, indices):
# https://github.com/pandas-dev/pandas/issues/22386
subset = data[:5]
data = pd.Series(subset, name="A")
expected = pd.Series(subset.take(indices, allow_fill=True), name="A")
if frame:
result = data.to_frame(name="A").assign(B=1).shift(periods)
expected = pd.concat(
[expected, pd.Series([1] * 5, name="B").shift(periods)], axis=1
)
compare = tm.assert_frame_equal
else:
result = data.shift(periods)
compare = tm.assert_series_equal
compare(result, expected)
def test_shift_0_periods(self, data):
# GH#33856 shifting with periods=0 should return a copy, not same obj
result = data.shift(0)
assert data[0] != data[1] # otherwise below is invalid
data[0] = data[1]
assert result[0] != result[1] # i.e. not the same object/view
@pytest.mark.parametrize("periods", [1, -2])
def test_diff(self, data, periods):
data = data[:5]
if is_bool_dtype(data.dtype):
op = operator.xor
else:
op = operator.sub
try:
# does this array implement ops?
op(data, data)
except Exception:
pytest.skip(f"{type(data)} does not support diff")
s = pd.Series(data)
result = s.diff(periods)
expected = pd.Series(op(data, data.shift(periods)))
tm.assert_series_equal(result, expected)
df = pd.DataFrame({"A": data, "B": [1.0] * 5})
result = df.diff(periods)
if periods == 1:
b = [np.nan, 0, 0, 0, 0]
else:
b = [0, 0, 0, np.nan, np.nan]
expected = pd.DataFrame({"A": expected, "B": b})
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"periods, indices",
[[-4, [-1, -1]], [-1, [1, -1]], [0, [0, 1]], [1, [-1, 0]], [4, [-1, -1]]],
)
def test_shift_non_empty_array(self, data, periods, indices):
# https://github.com/pandas-dev/pandas/issues/23911
subset = data[:2]
result = subset.shift(periods)
expected = subset.take(indices, allow_fill=True)
tm.assert_extension_array_equal(result, expected)
@pytest.mark.parametrize("periods", [-4, -1, 0, 1, 4])
def test_shift_empty_array(self, data, periods):
# https://github.com/pandas-dev/pandas/issues/23911
empty = data[:0]
result = empty.shift(periods)
expected = empty
tm.assert_extension_array_equal(result, expected)
def test_shift_zero_copies(self, data):
# GH#31502
result = data.shift(0)
assert result is not data
result = data[:0].shift(2)
assert result is not data
def test_shift_fill_value(self, data):
arr = data[:4]
fill_value = data[0]
result = arr.shift(1, fill_value=fill_value)
expected = data.take([0, 0, 1, 2])
tm.assert_extension_array_equal(result, expected)
result = arr.shift(-2, fill_value=fill_value)
expected = data.take([2, 3, 0, 0])
tm.assert_extension_array_equal(result, expected)
def test_not_hashable(self, data):
# We are in general mutable, so not hashable
with pytest.raises(TypeError, match="unhashable type"):
hash(data)
def test_hash_pandas_object_works(self, data, as_frame):
# https://github.com/pandas-dev/pandas/issues/23066
data = pd.Series(data)
if as_frame:
data = data.to_frame()
a = pd.util.hash_pandas_object(data)
b = pd.util.hash_pandas_object(data)
tm.assert_equal(a, b)
def test_searchsorted(self, data_for_sorting, as_series):
if data_for_sorting.dtype._is_boolean:
return self._test_searchsorted_bool_dtypes(data_for_sorting, as_series)
b, c, a = data_for_sorting
arr = data_for_sorting.take([2, 0, 1]) # to get [a, b, c]
if as_series:
arr = pd.Series(arr)
assert arr.searchsorted(a) == 0
assert arr.searchsorted(a, side="right") == 1
assert arr.searchsorted(b) == 1
assert arr.searchsorted(b, side="right") == 2
assert arr.searchsorted(c) == 2
assert arr.searchsorted(c, side="right") == 3
result = arr.searchsorted(arr.take([0, 2]))
expected = np.array([0, 2], dtype=np.intp)
tm.assert_numpy_array_equal(result, expected)
# sorter
sorter = np.array([1, 2, 0])
assert data_for_sorting.searchsorted(a, sorter=sorter) == 0
def _test_searchsorted_bool_dtypes(self, data_for_sorting, as_series):
# We call this from test_searchsorted in cases where we have a
# boolean-like dtype. The non-bool test assumes we have more than 2
# unique values.
dtype = data_for_sorting.dtype
data_for_sorting = pd.array([True, False], dtype=dtype)
b, a = data_for_sorting
arr = type(data_for_sorting)._from_sequence([a, b], dtype=dtype)
if as_series:
arr = pd.Series(arr)
assert arr.searchsorted(a) == 0
assert arr.searchsorted(a, side="right") == 1
assert arr.searchsorted(b) == 1
assert arr.searchsorted(b, side="right") == 2
result = arr.searchsorted(arr.take([0, 1]))
expected = np.array([0, 1], dtype=np.intp)
tm.assert_numpy_array_equal(result, expected)
# sorter
sorter = np.array([1, 0])
assert data_for_sorting.searchsorted(a, sorter=sorter) == 0
def test_where_series(self, data, na_value, as_frame):
assert data[0] != data[1]
cls = type(data)
a, b = data[:2]
orig = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype))
ser = orig.copy()
cond = np.array([True, True, False, False])
if as_frame:
ser = ser.to_frame(name="a")
cond = cond.reshape(-1, 1)
result = ser.where(cond)
expected = pd.Series(
cls._from_sequence([a, a, na_value, na_value], dtype=data.dtype)
)
if as_frame:
expected = expected.to_frame(name="a")
tm.assert_equal(result, expected)
ser.mask(~cond, inplace=True)
tm.assert_equal(ser, expected)
# array other
ser = orig.copy()
if as_frame:
ser = ser.to_frame(name="a")
cond = np.array([True, False, True, True])
other = cls._from_sequence([a, b, a, b], dtype=data.dtype)
if as_frame:
other = pd.DataFrame({"a": other})
cond = pd.DataFrame({"a": cond})
result = ser.where(cond, other)
expected = pd.Series(cls._from_sequence([a, b, b, b], dtype=data.dtype))
if as_frame:
expected = expected.to_frame(name="a")
tm.assert_equal(result, expected)
ser.mask(~cond, other, inplace=True)
tm.assert_equal(ser, expected)
@pytest.mark.parametrize("repeats", [0, 1, 2, [1, 2, 3]])
def test_repeat(self, data, repeats, as_series, use_numpy):
arr = type(data)._from_sequence(data[:3], dtype=data.dtype)
if as_series:
arr = pd.Series(arr)
result = np.repeat(arr, repeats) if use_numpy else arr.repeat(repeats)
repeats = [repeats] * 3 if isinstance(repeats, int) else repeats
expected = [x for x, n in zip(arr, repeats) for _ in range(n)]
expected = type(data)._from_sequence(expected, dtype=data.dtype)
if as_series:
expected = pd.Series(expected, index=arr.index.repeat(repeats))
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"repeats, kwargs, error, msg",
[
(2, {"axis": 1}, ValueError, "axis"),
(-1, {}, ValueError, "negative"),
([1, 2], {}, ValueError, "shape"),
(2, {"foo": "bar"}, TypeError, "'foo'"),
],
)
def test_repeat_raises(self, data, repeats, kwargs, error, msg, use_numpy):
with pytest.raises(error, match=msg):
if use_numpy:
np.repeat(data, repeats, **kwargs)
else:
data.repeat(repeats, **kwargs)
def test_delete(self, data):
result = data.delete(0)
expected = data[1:]
tm.assert_extension_array_equal(result, expected)
result = data.delete([1, 3])
expected = data._concat_same_type([data[[0]], data[[2]], data[4:]])
tm.assert_extension_array_equal(result, expected)
def test_insert(self, data):
# insert at the beginning
result = data[1:].insert(0, data[0])
tm.assert_extension_array_equal(result, data)
result = data[1:].insert(-len(data[1:]), data[0])
tm.assert_extension_array_equal(result, data)
# insert at the middle
result = data[:-1].insert(4, data[-1])
taker = np.arange(len(data))
taker[5:] = taker[4:-1]
taker[4] = len(data) - 1
expected = data.take(taker)
tm.assert_extension_array_equal(result, expected)
def test_insert_invalid(self, data, invalid_scalar):
item = invalid_scalar
with pytest.raises((TypeError, ValueError)):
data.insert(0, item)
with pytest.raises((TypeError, ValueError)):
data.insert(4, item)
with pytest.raises((TypeError, ValueError)):
data.insert(len(data) - 1, item)
def test_insert_invalid_loc(self, data):
ub = len(data)
with pytest.raises(IndexError):
data.insert(ub + 1, data[0])
with pytest.raises(IndexError):
data.insert(-ub - 1, data[0])
with pytest.raises(TypeError):
# we expect TypeError here instead of IndexError to match np.insert
data.insert(1.5, data[0])
@pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame])
def test_equals(self, data, na_value, as_series, box):
data2 = type(data)._from_sequence([data[0]] * len(data), dtype=data.dtype)
data_na = type(data)._from_sequence([na_value] * len(data), dtype=data.dtype)
data = tm.box_expected(data, box, transpose=False)
data2 = tm.box_expected(data2, box, transpose=False)
data_na = tm.box_expected(data_na, box, transpose=False)
# we are asserting with `is True/False` explicitly, to test that the
# result is an actual Python bool, and not something "truthy"
assert data.equals(data) is True
assert data.equals(data.copy()) is True
# unequal other data
assert data.equals(data2) is False
assert data.equals(data_na) is False
# different length
assert data[:2].equals(data[:3]) is False
# empty are equal
assert data[:0].equals(data[:0]) is True
# other types
assert data.equals(None) is False
assert data[[0]].equals(data[0]) is False
def test_equals_same_data_different_object(self, data):
# https://github.com/pandas-dev/pandas/issues/34660
assert pd.Series(data).equals(pd.Series(data))
|
BaseMethodsTests
|
python
|
wandb__wandb
|
wandb/automations/_generated/fragments.py
|
{
"start": 1535,
"end": 1713
}
|
class ____(GQLResult):
typename__: Typename[
Literal["GitHubOAuthIntegration", "Integration", "SlackIntegration"]
]
|
GenericWebhookActionFieldsIntegrationIntegration
|
python
|
django__django
|
tests/postgres_tests/test_hstore.py
|
{
"start": 680,
"end": 2387
}
|
class ____(PostgreSQLTestCase):
def test_save_load_success(self):
value = {"a": "b"}
instance = HStoreModel(field=value)
instance.save()
reloaded = HStoreModel.objects.get()
self.assertEqual(reloaded.field, value)
def test_null(self):
instance = HStoreModel(field=None)
instance.save()
reloaded = HStoreModel.objects.get()
self.assertIsNone(reloaded.field)
def test_value_null(self):
value = {"a": None}
instance = HStoreModel(field=value)
instance.save()
reloaded = HStoreModel.objects.get()
self.assertEqual(reloaded.field, value)
def test_key_val_cast_to_string(self):
value = {"a": 1, "b": "B", 2: "c", "ï": "ê"}
expected_value = {"a": "1", "b": "B", "2": "c", "ï": "ê"}
instance = HStoreModel.objects.create(field=value)
instance = HStoreModel.objects.get()
self.assertEqual(instance.field, expected_value)
instance = HStoreModel.objects.get(field__a=1)
self.assertEqual(instance.field, expected_value)
instance = HStoreModel.objects.get(field__has_keys=[2, "a", "ï"])
self.assertEqual(instance.field, expected_value)
def test_array_field(self):
value = [
{"a": 1, "b": "B", 2: "c", "ï": "ê"},
{"a": 1, "b": "B", 2: "c", "ï": "ê"},
]
expected_value = [
{"a": "1", "b": "B", "2": "c", "ï": "ê"},
{"a": "1", "b": "B", "2": "c", "ï": "ê"},
]
instance = HStoreModel.objects.create(array_field=value)
instance.refresh_from_db()
self.assertEqual(instance.array_field, expected_value)
|
SimpleTests
|
python
|
xlwings__xlwings
|
xlwings/constants.py
|
{
"start": 127822,
"end": 127972
}
|
class ____:
xlXmlImportSuccess = 0 # from enum XlXmlImportResult
xlXmlImportValidationFailed = 2 # from enum XlXmlImportResult
|
XmlImportResult
|
python
|
openai__openai-python
|
src/openai/resources/images.py
|
{
"start": 94356,
"end": 94817
}
|
class ____:
def __init__(self, images: AsyncImages) -> None:
self._images = images
self.create_variation = _legacy_response.async_to_raw_response_wrapper(
images.create_variation,
)
self.edit = _legacy_response.async_to_raw_response_wrapper(
images.edit,
)
self.generate = _legacy_response.async_to_raw_response_wrapper(
images.generate,
)
|
AsyncImagesWithRawResponse
|
python
|
readthedocs__readthedocs.org
|
readthedocs/api/v3/serializers.py
|
{
"start": 31173,
"end": 31396
}
|
class ____(serializers.ModelSerializer):
"""Serializer used to remove a subproject relationship to a Project."""
class Meta:
model = ProjectRelationship
fields = ("alias",)
|
SubprojectDestroySerializer
|
python
|
fsspec__filesystem_spec
|
fsspec/implementations/zip.py
|
{
"start": 95,
"end": 6072
}
|
class ____(AbstractArchiveFileSystem):
"""Read/Write contents of ZIP archive as a file-system
Keeps file object open while instance lives.
This class is pickleable, but not necessarily thread-safe
"""
root_marker = ""
protocol = "zip"
cachable = False
def __init__(
self,
fo="",
mode="r",
target_protocol=None,
target_options=None,
compression=zipfile.ZIP_STORED,
allowZip64=True,
compresslevel=None,
**kwargs,
):
"""
Parameters
----------
fo: str or file-like
Contains ZIP, and must exist. If a str, will fetch file using
:meth:`~fsspec.open_files`, which must return one file exactly.
mode: str
Accept: "r", "w", "a"
target_protocol: str (optional)
If ``fo`` is a string, this value can be used to override the
FS protocol inferred from a URL
target_options: dict (optional)
Kwargs passed when instantiating the target FS, if ``fo`` is
a string.
compression, allowZip64, compresslevel: passed to ZipFile
Only relevant when creating a ZIP
"""
super().__init__(self, **kwargs)
if mode not in set("rwa"):
raise ValueError(f"mode '{mode}' no understood")
self.mode = mode
if isinstance(fo, (str, os.PathLike)):
if mode == "a":
m = "r+b"
else:
m = mode + "b"
fo = fsspec.open(
fo, mode=m, protocol=target_protocol, **(target_options or {})
)
self.force_zip_64 = allowZip64
self.of = fo
self.fo = fo.__enter__() # the whole instance is a context
self.zip = zipfile.ZipFile(
self.fo,
mode=mode,
compression=compression,
allowZip64=allowZip64,
compresslevel=compresslevel,
)
self.dir_cache = None
@classmethod
def _strip_protocol(cls, path):
# zip file paths are always relative to the archive root
return super()._strip_protocol(path).lstrip("/")
def __del__(self):
if hasattr(self, "zip"):
self.close()
del self.zip
def close(self):
"""Commits any write changes to the file. Done on ``del`` too."""
self.zip.close()
def _get_dirs(self):
if self.dir_cache is None or self.mode in set("wa"):
# when writing, dir_cache is always in the ZipFile's attributes,
# not read from the file.
files = self.zip.infolist()
self.dir_cache = {
dirname.rstrip("/"): {
"name": dirname.rstrip("/"),
"size": 0,
"type": "directory",
}
for dirname in self._all_dirnames(self.zip.namelist())
}
for z in files:
f = {s: getattr(z, s, None) for s in zipfile.ZipInfo.__slots__}
f.update(
{
"name": z.filename.rstrip("/"),
"size": z.file_size,
"type": ("directory" if z.is_dir() else "file"),
}
)
self.dir_cache[f["name"]] = f
def pipe_file(self, path, value, **kwargs):
# override upstream, because we know the exact file size in this case
self.zip.writestr(path, value, **kwargs)
def _open(
self,
path,
mode="rb",
block_size=None,
autocommit=True,
cache_options=None,
**kwargs,
):
path = self._strip_protocol(path)
if "r" in mode and self.mode in set("wa"):
if self.exists(path):
raise OSError("ZipFS can only be open for reading or writing, not both")
raise FileNotFoundError(path)
if "r" in self.mode and "w" in mode:
raise OSError("ZipFS can only be open for reading or writing, not both")
out = self.zip.open(path, mode.strip("b"), force_zip64=self.force_zip_64)
if "r" in mode:
info = self.info(path)
out.size = info["size"]
out.name = info["name"]
return out
def find(self, path, maxdepth=None, withdirs=False, detail=False, **kwargs):
if maxdepth is not None and maxdepth < 1:
raise ValueError("maxdepth must be at least 1")
# Remove the leading slash, as the zip file paths are always
# given without a leading slash
path = path.lstrip("/")
path_parts = list(filter(lambda s: bool(s), path.split("/")))
def _matching_starts(file_path):
file_parts = filter(lambda s: bool(s), file_path.split("/"))
return all(a == b for a, b in zip(path_parts, file_parts))
self._get_dirs()
result = {}
# To match posix find, if an exact file name is given, we should
# return only that file
if path in self.dir_cache and self.dir_cache[path]["type"] == "file":
result[path] = self.dir_cache[path]
return result if detail else [path]
for file_path, file_info in self.dir_cache.items():
if not (path == "" or _matching_starts(file_path)):
continue
if file_info["type"] == "directory":
if withdirs:
if file_path not in result:
result[file_path.strip("/")] = file_info
continue
if file_path not in result:
result[file_path] = file_info if detail else None
if maxdepth:
path_depth = path.count("/")
result = {
k: v for k, v in result.items() if k.count("/") - path_depth < maxdepth
}
return result if detail else sorted(result)
|
ZipFileSystem
|
python
|
pallets__click
|
src/click/shell_completion.py
|
{
"start": 1417,
"end": 5583
}
|
class ____:
"""Represents a completion value and metadata about the value. The
default metadata is ``type`` to indicate special shell handling,
and ``help`` if a shell supports showing a help string next to the
value.
Arbitrary parameters can be passed when creating the object, and
accessed using ``item.attr``. If an attribute wasn't passed,
accessing it returns ``None``.
:param value: The completion suggestion.
:param type: Tells the shell script to provide special completion
support for the type. Click uses ``"dir"`` and ``"file"``.
:param help: String shown next to the value if supported.
:param kwargs: Arbitrary metadata. The built-in implementations
don't use this, but custom type completions paired with custom
shell support could use it.
"""
__slots__ = ("value", "type", "help", "_info")
def __init__(
self,
value: t.Any,
type: str = "plain",
help: str | None = None,
**kwargs: t.Any,
) -> None:
self.value: t.Any = value
self.type: str = type
self.help: str | None = help
self._info = kwargs
def __getattr__(self, name: str) -> t.Any:
return self._info.get(name)
# Only Bash >= 4.4 has the nosort option.
_SOURCE_BASH = """\
%(complete_func)s() {
local IFS=$'\\n'
local response
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
%(complete_var)s=bash_complete $1)
for completion in $response; do
IFS=',' read type value <<< "$completion"
if [[ $type == 'dir' ]]; then
COMPREPLY=()
compopt -o dirnames
elif [[ $type == 'file' ]]; then
COMPREPLY=()
compopt -o default
elif [[ $type == 'plain' ]]; then
COMPREPLY+=($value)
fi
done
return 0
}
%(complete_func)s_setup() {
complete -o nosort -F %(complete_func)s %(prog_name)s
}
%(complete_func)s_setup;
"""
# See ZshComplete.format_completion below, and issue #2703, before
# changing this script.
#
# (TL;DR: _describe is picky about the format, but this Zsh script snippet
# is already widely deployed. So freeze this script, and use clever-ish
# handling of colons in ZshComplet.format_completion.)
_SOURCE_ZSH = """\
#compdef %(prog_name)s
%(complete_func)s() {
local -a completions
local -a completions_with_descriptions
local -a response
(( ! $+commands[%(prog_name)s] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \
%(complete_var)s=zsh_complete %(prog_name)s)}")
for type key descr in ${response}; do
if [[ "$type" == "plain" ]]; then
if [[ "$descr" == "_" ]]; then
completions+=("$key")
else
completions_with_descriptions+=("$key":"$descr")
fi
elif [[ "$type" == "dir" ]]; then
_path_files -/
elif [[ "$type" == "file" ]]; then
_path_files -f
fi
done
if [ -n "$completions_with_descriptions" ]; then
_describe -V unsorted completions_with_descriptions -U
fi
if [ -n "$completions" ]; then
compadd -U -V unsorted -a completions
fi
}
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
# autoload from fpath, call function directly
%(complete_func)s "$@"
else
# eval/source/. command, register function for later
compdef %(complete_func)s %(prog_name)s
fi
"""
_SOURCE_FISH = """\
function %(complete_func)s;
set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
COMP_CWORD=(commandline -t) %(prog_name)s);
for completion in $response;
set -l metadata (string split "," $completion);
if test $metadata[1] = "dir";
__fish_complete_directories $metadata[2];
else if test $metadata[1] = "file";
__fish_complete_path $metadata[2];
else if test $metadata[1] = "plain";
echo $metadata[2];
end;
end;
end;
complete --no-files --command %(prog_name)s --arguments \
"(%(complete_func)s)";
"""
|
CompletionItem
|
python
|
spack__spack
|
var/spack/test_repos/spack_repo/builtin_mock/packages/maintainers_1/package.py
|
{
"start": 217,
"end": 484
}
|
class ____(Package):
"""Package with a maintainers field."""
homepage = "http://www.example.com"
url = "http://www.example.com/maintainers-1.0.tar.gz"
maintainers("user1", "user2")
version("1.0", md5="0123456789abcdef0123456789abcdef")
|
Maintainers1
|
python
|
pytorch__pytorch
|
torch/_inductor/ir.py
|
{
"start": 270184,
"end": 272620
}
|
class ____(ExternKernel):
"""
The result of a call to aten._assert_scalar
"""
def get_reads(self) -> OrderedSet[Dep]:
return OrderedSet()
def should_allocate(self) -> bool:
return False
def __init__(self, scalar: SympyBoolean, msg: str) -> None:
super().__init__(
# Buffer(name, layotu)
None,
NoneLayout(device=torch.device("cpu")),
# InputsKernel(inputs)
[],
)
self.scalar = scalar
self.msg = msg
def has_side_effects(self) -> bool:
return True
@cache_on_self_and_args("AssertScalar")
def get_free_symbol_uses(
self, unbacked_only: bool = False
) -> OrderedSet[sympy.Symbol]:
return get_free_symbols(self.scalar, unbacked_only)
def codegen(self, wrapper: PythonWrapperCodegen) -> None:
if not config.scalar_asserts:
return
# NB: It is EXTREMELY important not to simplify the scalar under assertion here,
# because simplify is done with respect to runtime asserts. So if you have
# "u0 == 0" in the runtime asserts, if you subsequently try to
# simplify(u0 == 0), you will get True (because we've already runtime assert'ed
# that it's true). But we're code generating the actual runtime assert here!!
symbol = next(iter(self.get_free_symbol_uses(unbacked_only=False)))
if V.graph.fx_wrapper:
# TODO fix
pass
elif V.graph.cpp_wrapper:
symbol_str = f"std::to_string({symbol})"
sizevar = V.graph.wrapper_code.codegen_cpp_sizevar(
self.scalar, simplify=False
)
# TODO: when we start compiling in C++20, annotate with [[unlikely]].
wrapper.writeline(
f'if (!({sizevar})) {{ throw std::runtime_error("Expected {self.msg} but received " + {symbol_str}); }}'
)
else:
sizevar = V.graph.wrapper_code.codegen_python_sizevar(
self.scalar, simplify=False
)
wrapper.writeline(f"if not ({sizevar}):")
wrapper.writeline(f" raise RuntimeError({repr(self.msg)})")
# No one should ever use this buffer, but for uniformity
# define the variable and assign it None
wrapper.writeline(f"{self.get_name()} = None")
@ir_dataclass(frozen=False)
|
AssertScalar
|
python
|
catalyst-team__catalyst
|
catalyst/engines/torch.py
|
{
"start": 868,
"end": 1234
}
|
class ____(Engine):
"""Multi-GPU-based engine."""
def __init__(self, *args, **kwargs) -> None:
"""Init."""
super().__init__(*args, cpu=False, **kwargs)
def prepare_model(self, model):
"""Overrides."""
model = torch.nn.DataParallel(model)
model = super().prepare_model(model)
return model
|
DataParallelEngine
|
python
|
oauthlib__oauthlib
|
examples/device_code_flow.py
|
{
"start": 7671,
"end": 7892
}
|
class ____:
def __init__(self):
validator = ExampleRequestValidator
self.server = Server(validator)
# You should already have the /token endpoint implemented in your provider.
|
ServerSetupForTokenEndpoint
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/sql/type_api.py
|
{
"start": 3033,
"end": 3156
}
|
class ____(TypedDict):
impl: TypeEngine[Any]
result: Dict[Any, Optional[_ResultProcessorType[Any]]]
|
_BaseTypeMemoDict
|
python
|
gevent__gevent
|
src/gevent/testing/leakcheck.py
|
{
"start": 1928,
"end": 8227
}
|
class ____(object):
# Some builtin things that we ignore.
# For awhile, we also ignored types.FrameType and types.TracebackType,
# but those are important and often involved in leaks.
IGNORED_TYPES = (tuple, dict,)
try:
CALLBACK_KIND = gevent.core.callback
except AttributeError:
# Must be using FFI.
from gevent._ffi.callback import callback as CALLBACK_KIND
def __init__(self, testcase, function):
self.testcase = testcase
self.function = function
self.deltas = []
self.peak_stats = {}
# The very first time we are called, we have already been
# self.setUp() by the test runner, so we don't need to do it again.
self.needs_setUp = False
def _ignore_object_p(self, obj):
if obj is self:
return False
try:
# Certain badly written __eq__ and __contains__ methods
# (I'm looking at you, Python 3.10 importlib.metadata._text!
# ``__eq__(self, other): return self.lower() == other.lower()``)
# raise AttributeError which propagates here, and must be caught.
# Similarly, we can get a TypeError
if (
obj in self.__dict__.values()
or obj == self._ignore_object_p # pylint:disable=comparison-with-callable
):
return False
except (AttributeError, TypeError):
# `obj` is things like that _text class. Also have seen
# - psycopg2._psycopg.type
# - relstorage.adapters.drivers._ClassDriverFactory
return True
kind = type(obj)
if kind in self.IGNORED_TYPES:
return False
if kind is self.CALLBACK_KIND and obj.callback is None and obj.args is None:
# these represent callbacks that have been stopped, but
# the event loop hasn't cycled around to run them. The only
# known cause of this is killing greenlets before they get a chance
# to run for the first time.
return False
return True
def _growth(self):
return objgraph.growth(limit=None, peak_stats=self.peak_stats, filter=self._ignore_object_p)
def _report_diff(self, growth):
if not growth:
return "<Unable to calculate growth>"
lines = []
width = max(len(name) for name, _, _ in growth)
for name, count, delta in growth:
lines.append('%-*s%9d %+9d' % (width, name, count, delta))
diff = '\n'.join(lines)
return diff
def _run_test(self, args, kwargs):
gc_enabled = gc.isenabled()
gc.disable()
if self.needs_setUp:
self.testcase.setUp()
self.testcase.skipTearDown = False
try:
self.function(self.testcase, *args, **kwargs)
finally:
self.testcase.tearDown()
self.testcase.doCleanups()
self.testcase.skipTearDown = True
self.needs_setUp = True
if gc_enabled:
gc.enable()
def _growth_after(self):
# Grab post snapshot
if 'urlparse' in sys.modules:
sys.modules['urlparse'].clear_cache()
if 'urllib.parse' in sys.modules:
sys.modules['urllib.parse'].clear_cache() # pylint:disable=no-member
return self._growth()
def _check_deltas(self, growth):
# Return false when we have decided there is no leak,
# true if we should keep looping, raises an assertion
# if we have decided there is a leak.
deltas = self.deltas
if not deltas:
# We haven't run yet, no data, keep looping
return True
if gc.garbage:
raise AssertionError("Generated uncollectable garbage %r" % (gc.garbage,))
# the following configurations are classified as "no leak"
# [0, 0]
# [x, 0, 0]
# [... a, b, c, d] where a+b+c+d = 0
#
# the following configurations are classified as "leak"
# [... z, z, z] where z > 0
if deltas[-2:] == [0, 0] and len(deltas) in (2, 3):
return False
if deltas[-3:] == [0, 0, 0]:
return False
if len(deltas) >= 4 and sum(deltas[-4:]) == 0:
return False
if len(deltas) >= 3 and deltas[-1] > 0 and deltas[-1] == deltas[-2] and deltas[-2] == deltas[-3]:
diff = self._report_diff(growth)
raise AssertionError('refcount increased by %r\n%s' % (deltas, diff))
# OK, we don't know for sure yet. Let's search for more
if sum(deltas[-3:]) <= 0 or sum(deltas[-4:]) <= 0 or deltas[-4:].count(0) >= 2:
# this is suspicious, so give a few more runs
limit = 11
else:
limit = 7
if len(deltas) >= limit:
raise AssertionError('refcount increased by %r\n%s'
% (deltas,
self._report_diff(growth)))
# We couldn't decide yet, keep going
return True
def __call__(self, args, kwargs):
for _ in range(3):
gc.collect()
# Capture state before; the incremental will be
# updated by each call to _growth_after
growth = self._growth()
while self._check_deltas(growth):
self._run_test(args, kwargs)
growth = self._growth_after()
self.deltas.append(sum((stat[2] for stat in growth)))
def wrap_refcount(method):
if objgraph is None or getattr(method, 'ignore_leakcheck', False):
if objgraph is None:
import warnings
warnings.warn("objgraph not available, leakchecks disabled")
@wraps(method)
def _method_skipped_during_leakcheck(self, *_args, **_kwargs):
self.skipTest("This method ignored during leakchecks")
return _method_skipped_during_leakcheck
@wraps(method)
def wrapper(self, *args, **kwargs): # pylint:disable=too-many-branches
if getattr(self, 'ignore_leakcheck', False):
raise unittest.SkipTest("This class ignored during leakchecks")
return _RefCountChecker(self, method)(args, kwargs)
return wrapper
|
_RefCountChecker
|
python
|
Textualize__textual
|
tests/test_binding_inheritance.py
|
{
"start": 18888,
"end": 20560
}
|
class ____(AppKeyRecorder):
"""An app with a non-default screen that handles movement key bindings, child no-inherit."""
SCREENS = {"main": ScreenWithMovementBindingsNoInheritEmptyChild}
def on_mount(self) -> None:
self.push_screen("main")
async def test_focused_child_widget_no_inherit_empty_bindings_with_movement_bindings_on_screen() -> (
None
):
"""A focused child widget, that doesn't inherit bindings and sets BINDINGS empty, with movement bindings in the screen, should trigger screen actions."""
async with AppWithScreenWithBindingsWidgetEmptyBindingsNoInherit().run_test() as pilot:
await pilot.press(*AppKeyRecorder.ALL_KEYS)
pilot.app.all_recorded("screenly_")
##############################################################################
# Testing priority of overlapping bindings.
#
# Here we we'll have an app, screen, and a focused widget, along with a
# combination of overlapping bindings, each with different forms of
# priority, so we can check who wins where.
#
# Here are the permutations tested, with the expected winner:
#
# |-----|----------|----------|----------|--------|
# | Key | App | Screen | Widget | Winner |
# |-----|----------|----------|----------|--------|
# | 0 | | | | Widget |
# | A | Priority | | | App |
# | B | | Priority | | Screen |
# | C | | | Priority | Widget |
# | D | Priority | Priority | | App |
# | E | Priority | | Priority | App |
# | F | | Priority | Priority | Screen |
|
AppWithScreenWithBindingsWidgetEmptyBindingsNoInherit
|
python
|
airbytehq__airbyte
|
airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py
|
{
"start": 13909,
"end": 17468
}
|
class ____(CheckDocumentationContent):
name = "Prerequisites section of the documentation describes all required fields from specification"
description = (
"The user facing connector documentation should update `Prerequisites`"
" section with description for all required fields from source specification. "
"Having described all required fields in a one place helps Airbyte users easily set up the source connector. \n"
"If spec has required credentials/access_token/refresh_token etc, "
'check searches for one of ["account", "auth", "credentials", "access", "client"] words. '
"No need to add credentials/access_token/refresh_token etc to the section"
)
PREREQUISITES = "Prerequisites"
CREDENTIALS_KEYWORDS = ["account", "auth", "credentials", "access", "client"]
def check_prerequisites(self, connector: Connector) -> List[str]:
actual_connector_spec = connector.connector_spec_file_content
if not actual_connector_spec:
return []
documentation = DocumentationContent(connector=connector)
if self.PREREQUISITES not in documentation.headers:
return [f"Documentation does not have {self.PREREQUISITES} section."]
section_content = documentation.section(self.PREREQUISITES)
if section_content is None:
return [f"Documentation {self.PREREQUISITES} section is empty"]
if len(section_content) > 1:
return [f"Documentation has more than one {self.PREREQUISITES} section. Please check it."]
section_text = section_content[0].lower()
spec = actual_connector_spec.get("connectionSpecification") or actual_connector_spec.get("connection_specification")
required_titles, has_credentials = required_titles_from_spec(spec) # type: ignore
missing_fields: List[str] = []
for title in required_titles:
if title.lower() not in section_text:
missing_fields.append(title)
if has_credentials:
credentials_validation = [k in section_text for k in self.CREDENTIALS_KEYWORDS]
if True not in credentials_validation:
missing_fields.append("credentials")
return missing_fields
def _run(self, connector: Connector) -> CheckResult:
if not connector.documentation_file_path or not connector.documentation_file_path.exists():
return self.fail(
connector=connector,
message="Could not check documentation structure as the documentation file is missing.",
)
if not connector.documentation_file_path.read_text():
return self.fail(
connector=connector,
message="Documentation file is empty",
)
# check_prerequisites uses spec content from file, not from spec command,
# which possible can lead to incorrect testing, for now it works for connectors with sl>=300.
# But if someone faced with unexpected behavior of this test it's better to disable it.
errors = self.check_prerequisites(connector)
if errors:
return self.fail(
connector=connector,
message=f"Missing descriptions for required spec fields: {'. '.join(errors)}",
)
return self.pass_(
connector=connector,
message="All required fields from spec are present in the connector documentation",
)
|
CheckPrerequisitesSectionDescribesRequiredFieldsFromSpec
|
python
|
dask__distributed
|
distributed/tests/test_nanny.py
|
{
"start": 3446,
"end": 17508
}
|
class ____(Worker):
# a subclass of Worker which is not Worker
pass
@gen_cluster(client=True, Worker=Nanny)
async def test_nanny_worker_class(c, s, w1, w2):
out = await c._run(lambda dask_worker=None: str(dask_worker.__class__))
assert "Worker" in list(out.values())[0]
assert w1.Worker is Worker
@gen_cluster(client=True, Worker=Nanny, worker_kwargs={"worker_class": Something})
async def test_nanny_alt_worker_class(c, s, w1, w2):
out = await c._run(lambda dask_worker=None: str(dask_worker.__class__))
assert "Something" in list(out.values())[0]
assert w1.Worker is Something
@pytest.mark.slow
@gen_cluster(nthreads=[])
async def test_nanny_death_timeout(s):
await s.close()
w = Nanny(s.address, death_timeout=1)
with pytest.raises(TimeoutError):
await w
assert w.status == Status.failed
@gen_cluster(client=True, Worker=Nanny)
async def test_random_seed(c, s, a, b):
async def check_func(func):
x = c.submit(func, 0, 2**31, pure=False, workers=a.worker_address)
y = c.submit(func, 0, 2**31, pure=False, workers=b.worker_address)
assert x.key != y.key
x = await x
y = await y
assert x != y
await check_func(lambda a, b: random.randint(a, b))
np = pytest.importorskip("numpy")
await check_func(lambda a, b: np.random.randint(a, b))
@pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows")
@gen_cluster(nthreads=[])
async def test_num_fds(s):
proc = psutil.Process()
# Warm up
async with Nanny(s.address):
pass
with profile.lock:
gc.collect()
before = proc.num_fds()
for _ in range(3):
async with Nanny(s.address):
await asyncio.sleep(0.1)
while proc.num_fds() > before:
print("fds:", before, proc.num_fds())
await asyncio.sleep(0.1)
@pytest.mark.skipif(not LINUX, reason="Need 127.0.0.2 to mean localhost")
@gen_cluster(client=True, nthreads=[])
async def test_worker_uses_same_host_as_nanny(c, s):
for host in ["tcp://0.0.0.0", "tcp://127.0.0.2"]:
async with Nanny(s.address, host=host):
def func(dask_worker):
return dask_worker.listener.listen_address
result = await c.run(func)
assert host in first(result.values())
@gen_test()
async def test_scheduler_file():
with tmpfile() as fn:
s = await Scheduler(scheduler_file=fn, dashboard_address=":0")
async with Nanny(scheduler_file=fn) as n:
assert set(s.workers) == {n.worker_address}
s.stop()
@gen_cluster(client=True, Worker=Nanny, nthreads=[("", 1)])
async def test_nanny_restart(c, s, a):
x = await c.scatter(123)
assert await c.submit(lambda: 1) == 1
await a.restart()
while x.status != "cancelled":
await asyncio.sleep(0.1)
assert await c.submit(lambda: 1) == 1
@gen_cluster(client=True, Worker=Nanny, nthreads=[("", 1)])
async def test_nanny_restart_timeout(c, s, a):
x = await c.scatter(123)
with captured_logger(
logging.getLogger("distributed.nanny"), level=logging.ERROR
) as logger:
await a.restart(timeout=0)
out = logger.getvalue()
assert "timed out" in out.lower()
while x.status != "cancelled":
await asyncio.sleep(0.1)
assert await c.submit(lambda: 1) == 1
@gen_cluster(client=True, Worker=Nanny, nthreads=[("", 1)])
async def test_nanny_restart_timeout_stress(c, s, a):
x = await c.scatter(123)
restarts = [a.restart(timeout=random.random()) for _ in range(100)]
await asyncio.gather(*restarts)
while x.status != "cancelled":
await asyncio.sleep(0.1)
assert await c.submit(lambda: 1) == 1
assert len(s.workers) == 1
@gen_cluster(
nthreads=[("", 1)] * 8,
client=True,
clean_kwargs={"threads": False},
config={"distributed.worker.memory.pause": False},
)
async def test_throttle_outgoing_transfers(c, s, a, *other_workers):
# Put a bunch of small data on worker a
logging.getLogger("distributed.worker").setLevel(logging.DEBUG)
remote_data = c.map(
lambda x: b"0" * 10000, range(10), pure=False, workers=[a.address]
)
await wait(remote_data)
a.status = Status.paused
a.transfer_outgoing_count = 2
requests = [
await a.get_data(await w.rpc.connect(w.address), keys=[f.key], who=w.address)
for w in other_workers
for f in remote_data
]
await wait(requests)
wlogs = await c.get_worker_logs(workers=[a.address])
wlogs = "\n".join(x[1] for x in wlogs[a.address])
assert "throttling" in wlogs.lower()
@gen_cluster(nthreads=[])
async def test_scheduler_address_config(s):
with dask.config.set({"scheduler-address": s.address}):
async with Nanny() as nanny:
assert nanny.scheduler.address == s.address
while not s.workers:
await asyncio.sleep(0.01)
@pytest.mark.slow
@gen_test()
async def test_wait_for_scheduler():
with captured_logger("distributed") as log:
w = Nanny("127.0.0.1:44737")
IOLoop.current().add_callback(w.start)
await asyncio.sleep(6)
await w.close()
log = log.getvalue()
assert "error" not in log.lower(), log
assert "restart" not in log.lower(), log
@gen_cluster(nthreads=[], client=True)
async def test_environment_variable(c, s):
a = Nanny(s.address, memory_limit=0, env={"FOO": "123"})
b = Nanny(s.address, memory_limit=0, env={"FOO": "456"})
await asyncio.gather(a, b)
results = await c.run(lambda: os.environ["FOO"])
assert results == {a.worker_address: "123", b.worker_address: "456"}
await asyncio.gather(a.close(), b.close())
@gen_cluster(nthreads=[], client=True)
async def test_environment_variable_by_config(c, s, monkeypatch):
with dask.config.set({"distributed.nanny.environ": "456"}):
with pytest.raises(TypeError, match="configuration must be of type dict"):
Nanny(s.address, memory_limit=0)
with dask.config.set({"distributed.nanny.environ": {"FOO": "456"}}):
# precedence
# kwargs > env var > config
with mock.patch.dict(os.environ, {"FOO": "BAR"}, clear=True):
a = Nanny(s.address, memory_limit=0, env={"FOO": "123"})
x = Nanny(s.address, memory_limit=0)
b = Nanny(s.address, memory_limit=0)
await asyncio.gather(a, b, x)
results = await c.run(lambda: os.environ["FOO"])
assert results == {
a.worker_address: "123",
b.worker_address: "456",
x.worker_address: "BAR",
}
await asyncio.gather(a.close(), b.close(), x.close())
@gen_cluster(
nthreads=[],
client=True,
config={"distributed.nanny.environ": {"A": 1, "B": 2, "D": 4}},
)
async def test_environment_variable_config(c, s, monkeypatch):
monkeypatch.setenv("D", "123")
async with Nanny(s.address, env={"B": 3, "C": 4}) as n:
results = await c.run(lambda: os.environ)
assert results[n.worker_address]["A"] == "1"
assert results[n.worker_address]["B"] == "3"
assert results[n.worker_address]["C"] == "4"
assert results[n.worker_address]["D"] == "123"
@gen_cluster(
nthreads=[("", 1)],
client=True,
Worker=Nanny,
config={
"distributed.nanny.pre-spawn-environ": {"PRE-SPAWN": 1},
"distributed.nanny.environ": {"POST-SPAWN": 2},
},
)
async def test_environment_variable_pre_post_spawn(c, s, n):
assert n.env == {"PRE-SPAWN": "1", "POST-SPAWN": "2", "PYTHONHASHSEED": "6640"}
results = await c.run(lambda: os.environ)
assert results[n.worker_address]["PRE-SPAWN"] == "1"
assert results[n.worker_address]["POST-SPAWN"] == "2"
# if unset in pre-spawn-environ config, PYTHONHASHSEED defaults to "6640" to ensure
# consistent hashing across workers; https://github.com/dask/distributed/issues/4141
assert results[n.worker_address]["PYTHONHASHSEED"] == "6640"
del os.environ["PRE-SPAWN"]
assert "POST-SPAWN" not in os.environ
@gen_cluster(
nthreads=[],
client=True,
config={
"distributed.nanny.pre-spawn-environ.PRE1": 1,
"distributed.nanny.pre-spawn-environ.PRE2": 2,
"distributed.nanny.pre-spawn-environ.PRE3": 3,
"distributed.nanny.environ.POST1": 4,
"distributed.nanny.environ.POST2": 5,
"distributed.nanny.environ.POST3": 6,
},
)
async def test_environment_variable_overlay(c, s):
"""You can set a value to None to unset a variable in a config overlay"""
# Not the same as running Nanny(config=...), which would not work for pre-spawn
# variables
with dask.config.set(
{
"distributed.nanny.pre-spawn-environ.PRE2": 7,
"distributed.nanny.pre-spawn-environ.PRE3": None,
"distributed.nanny.environ.POST2": 8,
"distributed.nanny.environ.POST3": None,
},
):
async with Nanny(s.address):
env = await c.submit(lambda: os.environ)
assert env["PRE1"] == "1"
assert env["PRE2"] == "7"
assert "PRE3" not in env
assert env["POST1"] == "4"
assert env["POST2"] == "8"
assert "POST3" not in env
@gen_cluster(client=True, nthreads=[])
async def test_config_param_overlays(c, s):
with dask.config.set({"test123.foo": 1, "test123.bar": 2}):
async with Nanny(s.address, config={"test123.bar": 3, "test123.baz": 4}) as n:
out = await c.submit(lambda: dask.config.get("test123"))
assert out == {"foo": 1, "bar": 3, "baz": 4}
@gen_cluster(nthreads=[])
async def test_local_directory(s):
with tmpfile() as fn:
with dask.config.set(temporary_directory=fn):
async with Nanny(s.address) as n:
assert n.local_directory.startswith(fn)
assert "dask-scratch-space" in n.local_directory
assert n.process.worker_dir.count("dask-scratch-space") == 1
@pytest.mark.skipif(
WINDOWS or os.getuid() == 0,
reason="Need POSIX filesystem permissions and UIDs and Must not be root",
)
@gen_cluster(nthreads=[])
async def test_unwriteable_dask_worker_space(s, tmp_path):
os.mkdir(f"{tmp_path}/dask-scratch-space", mode=0o500)
with pytest.raises(PermissionError):
open(f"{tmp_path}/dask-scratch-space/tryme", "w")
with dask.config.set(temporary_directory=tmp_path):
async with Nanny(s.address) as n:
assert n.local_directory == os.path.join(
tmp_path, f"dask-scratch-space-{os.getuid()}"
)
assert n.process.worker_dir.count(f"dask-scratch-space-{os.getuid()}") == 1
def _noop(x):
"""Define here because closures aren't pickleable."""
pass
@gen_cluster(
nthreads=[("127.0.0.1", 1)],
client=True,
Worker=Nanny,
config={"distributed.worker.daemon": False},
)
async def test_mp_process_worker_no_daemon(c, s, a):
def multiprocessing_worker():
p = mp.Process(target=_noop, args=(None,))
p.start()
p.join()
await c.submit(multiprocessing_worker)
@gen_cluster(
nthreads=[("127.0.0.1", 1)],
client=True,
Worker=Nanny,
config={"distributed.worker.daemon": False},
)
async def test_mp_pool_worker_no_daemon(c, s, a):
def pool_worker(world_size):
with mp.Pool(processes=world_size) as p:
p.map(_noop, range(world_size))
await c.submit(pool_worker, 4)
@gen_cluster(nthreads=[])
async def test_nanny_closes_cleanly(s):
async with Nanny(s.address) as n:
assert n.process.pid
proc = n.process.process
assert not n.process
assert not proc.is_alive()
assert proc.exitcode == 0
@pytest.mark.slow
@gen_cluster(nthreads=[], timeout=60)
async def test_lifetime(s):
counter = 0
event = asyncio.Event()
class Plugin(SchedulerPlugin):
def add_worker(self, **kwargs):
pass
def remove_worker(self, **kwargs):
nonlocal counter
counter += 1
if counter == 2: # wait twice, then trigger closing event
event.set()
s.add_plugin(Plugin())
async with Nanny(s.address):
async with Nanny(s.address, lifetime="500 ms", lifetime_restart=True):
await event.wait()
@gen_cluster(client=True, nthreads=[])
async def test_nanny_closes_cleanly_if_worker_is_terminated(c, s):
async with Nanny(s.address) as n:
async with c.rpc(n.worker_address) as w:
IOLoop.current().add_callback(w.terminate)
start = time()
while n.status != Status.closed:
await asyncio.sleep(0.01)
assert time() < start + 5
assert n.status == Status.closed
@gen_cluster(client=True, nthreads=[])
async def test_config(c, s):
async with Nanny(s.address, config={"foo": "bar"}) as n:
config = await c.run(dask.config.get, "foo")
assert config[n.worker_address] == "bar"
@gen_cluster(client=True, nthreads=[])
async def test_nanny_port_range(c, s):
nanny_port = "9867:9868"
worker_port = "9869:9870"
async with Nanny(s.address, port=nanny_port, worker_port=worker_port) as n1:
assert n1.port == 9867 # Selects first port in range
async with Nanny(s.address, port=nanny_port, worker_port=worker_port) as n2:
assert n2.port == 9868 # Selects next port in range
with raises_with_cause(
RuntimeError,
"Nanny failed to start.",
ValueError,
"with port 9867:9868",
): # No more ports left
async with Nanny(s.address, port=nanny_port, worker_port=worker_port):
pass
# Ensure Worker ports are in worker_port range
def get_worker_port(dask_worker):
return dask_worker.port
worker_ports = await c.run(get_worker_port)
assert list(worker_ports.values()) == parse_ports(worker_port)
|
Something
|
python
|
apache__airflow
|
providers/google/tests/unit/google/cloud/operators/test_pubsub.py
|
{
"start": 14040,
"end": 18763
}
|
class ____:
def _generate_messages(self, count):
return [
ReceivedMessage(
ack_id=f"{i}",
message={
"data": f"Message {i}".encode(),
"attributes": {"type": "generated message"},
},
)
for i in range(1, count + 1)
]
def _generate_dicts(self, count):
return [ReceivedMessage.to_dict(m) for m in self._generate_messages(count)]
@mock.patch("airflow.providers.google.cloud.operators.pubsub.PubSubHook")
def test_execute_no_messages(self, mock_hook):
operator = PubSubPullOperator(
task_id=TASK_ID,
project_id=TEST_PROJECT,
subscription=TEST_SUBSCRIPTION,
)
mock_hook.return_value.pull.return_value = []
assert operator.execute({}) == []
@mock.patch("airflow.providers.google.cloud.operators.pubsub.PubSubHook")
def test_execute_with_ack_messages(self, mock_hook):
operator = PubSubPullOperator(
task_id=TASK_ID,
project_id=TEST_PROJECT,
subscription=TEST_SUBSCRIPTION,
ack_messages=True,
)
generated_messages = self._generate_messages(5)
generated_dicts = self._generate_dicts(5)
mock_hook.return_value.pull.return_value = generated_messages
assert generated_dicts == operator.execute({})
mock_hook.return_value.acknowledge.assert_called_once_with(
project_id=TEST_PROJECT,
subscription=TEST_SUBSCRIPTION,
messages=generated_messages,
)
@mock.patch("airflow.providers.google.cloud.operators.pubsub.PubSubHook")
def test_execute_with_messages_callback(self, mock_hook):
generated_messages = self._generate_messages(5)
messages_callback_return_value = "asdfg"
def messages_callback(
pulled_messages: list[ReceivedMessage],
context: dict[str, Any],
):
assert pulled_messages == generated_messages
assert isinstance(context, dict)
for key in context.keys():
assert isinstance(key, str)
return messages_callback_return_value
messages_callback = mock.Mock(side_effect=messages_callback)
operator = PubSubPullOperator(
task_id=TASK_ID,
project_id=TEST_PROJECT,
subscription=TEST_SUBSCRIPTION,
messages_callback=messages_callback,
)
mock_hook.return_value.pull.return_value = generated_messages
response = operator.execute({})
mock_hook.return_value.pull.assert_called_once_with(
project_id=TEST_PROJECT, subscription=TEST_SUBSCRIPTION, max_messages=5, return_immediately=True
)
messages_callback.assert_called_once()
assert response == messages_callback_return_value
@pytest.mark.db_test
@mock.patch("airflow.providers.google.cloud.operators.pubsub.PubSubHook")
def test_execute_deferred(self, mock_hook, create_task_instance_of_operator):
"""
Asserts that a task is deferred and a PubSubPullOperator will be fired
when the PubSubPullOperator is executed with deferrable=True.
"""
ti = create_task_instance_of_operator(
PubSubPullOperator,
dag_id="dag_id",
task_id=TASK_ID,
project_id=TEST_PROJECT,
subscription=TEST_SUBSCRIPTION,
deferrable=True,
)
with pytest.raises(TaskDeferred) as _:
ti.task.execute(mock.MagicMock())
@mock.patch("airflow.providers.google.cloud.operators.pubsub.PubSubHook")
def test_get_openlineage_facets(self, mock_hook):
operator = PubSubPullOperator(
task_id=TASK_ID,
project_id=TEST_PROJECT,
subscription=TEST_SUBSCRIPTION,
)
generated_messages = self._generate_messages(5)
generated_dicts = self._generate_dicts(5)
mock_hook.return_value.pull.return_value = generated_messages
assert generated_dicts == operator.execute({})
mock_hook.return_value.pull.assert_called_once_with(
project_id=TEST_PROJECT, subscription=TEST_SUBSCRIPTION, max_messages=5, return_immediately=True
)
result = operator.get_openlineage_facets_on_complete(operator)
assert not result.run_facets
assert not result.job_facets
assert len(result.inputs) == 0
assert len(result.outputs) == 1
assert result.outputs[0].namespace == "pubsub"
assert result.outputs[0].name == f"subscription:{TEST_PROJECT}:{TEST_SUBSCRIPTION}"
|
TestPubSubPullOperator
|
python
|
dagster-io__dagster
|
python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py
|
{
"start": 8499,
"end": 57107
}
|
class ____(graphene.ObjectType):
# NOTE: properties/resolvers are listed alphabetically
assetKey = graphene.NonNull(GrapheneAssetKey)
assetMaterializations = graphene.Field(
non_null_list(GrapheneMaterializationEvent),
partitions=graphene.List(graphene.NonNull(graphene.String)),
beforeTimestampMillis=graphene.String(),
limit=graphene.Int(),
)
assetMaterializationUsedData = graphene.Field(
non_null_list(GrapheneMaterializationUpstreamDataVersion),
timestampMillis=graphene.NonNull(graphene.String),
)
assetObservations = graphene.Field(
non_null_list(GrapheneObservationEvent),
partitions=graphene.List(graphene.NonNull(graphene.String)),
beforeTimestampMillis=graphene.String(),
limit=graphene.Int(),
)
lastAutoMaterializationEvaluationRecord = graphene.Field(
GrapheneAutoMaterializeAssetEvaluationRecord,
asOfEvaluationId=graphene.ID(),
)
backfillPolicy = graphene.Field(GrapheneBackfillPolicy)
changedReasons = graphene.Field(non_null_list(GrapheneAssetChangedReason))
computeKind = graphene.String()
configField = graphene.Field(GrapheneConfigTypeField)
dataVersion = graphene.Field(graphene.String(), partition=graphene.String())
dataVersionByPartition = graphene.Field(
graphene.NonNull(graphene.List(graphene.String)),
partitions=graphene.List(graphene.NonNull(graphene.String)),
)
dependedBy = non_null_list(GrapheneAssetDependency)
dependedByKeys = non_null_list(GrapheneAssetKey)
dependencies = non_null_list(GrapheneAssetDependency)
dependencyKeys = non_null_list(GrapheneAssetKey)
description = graphene.String()
freshnessInfo = graphene.Field(GrapheneAssetFreshnessInfo)
freshnessPolicy = graphene.Field(GrapheneFreshnessPolicy)
freshnessStatusInfo = graphene.Field(GrapheneFreshnessStatusInfo)
internalFreshnessPolicy = graphene.Field(GrapheneInternalFreshnessPolicy)
autoMaterializePolicy = graphene.Field(GrapheneAutoMaterializePolicy)
automationCondition = graphene.Field(GrapheneAutomationCondition)
graphName = graphene.String()
groupName = graphene.NonNull(graphene.String)
owners = non_null_list(GrapheneAssetOwner)
id = graphene.NonNull(graphene.ID)
isExecutable = graphene.NonNull(graphene.Boolean)
isObservable = graphene.NonNull(graphene.Boolean)
isMaterializable = graphene.NonNull(graphene.Boolean)
isPartitioned = graphene.NonNull(graphene.Boolean)
isAutoCreatedStub = graphene.NonNull(graphene.Boolean)
jobNames = non_null_list(graphene.String)
jobs = non_null_list(GraphenePipeline)
latestMaterializationByPartition = graphene.Field(
graphene.NonNull(graphene.List(GrapheneMaterializationEvent)),
partitions=graphene.List(graphene.NonNull(graphene.String)),
)
latestRunForPartition = graphene.Field(GrapheneRun, partition=graphene.NonNull(graphene.String))
assetPartitionStatuses = graphene.NonNull(GrapheneAssetPartitionStatuses)
partitionStats = graphene.Field(GraphenePartitionStats)
metadata_entries = non_null_list(GrapheneMetadataEntry)
tags = non_null_list(GrapheneDefinitionTag)
kinds = non_null_list(graphene.String)
op = graphene.Field(GrapheneSolidDefinition)
opName = graphene.String()
opNames = non_null_list(graphene.String)
opVersion = graphene.String()
partitionDefinition = graphene.Field(GraphenePartitionDefinition)
partitionKeys = non_null_list(graphene.String)
partitionKeyConnection = graphene.Field(
GraphenePartitionKeyConnection,
limit=graphene.Argument(graphene.NonNull(graphene.Int)),
ascending=graphene.Argument(graphene.NonNull(graphene.Boolean)),
cursor=graphene.Argument(graphene.String),
)
partitionKeysByDimension = graphene.Field(
non_null_list(GrapheneDimensionPartitionKeys),
startIdx=graphene.Int(),
endIdx=graphene.Int(),
)
pools = non_null_list(graphene.String)
repository = graphene.NonNull(lambda: external.GrapheneRepository)
required_resources = non_null_list(GrapheneResourceRequirement)
staleStatus = graphene.Field(GrapheneAssetStaleStatus, partition=graphene.String())
staleStatusByPartition = graphene.Field(
non_null_list(GrapheneAssetStaleStatus),
partitions=graphene.List(graphene.NonNull(graphene.String)),
)
staleCauses = graphene.Field(
non_null_list(GrapheneAssetStaleCause), partition=graphene.String()
)
staleCausesByPartition = graphene.Field(
graphene.List(non_null_list(GrapheneAssetStaleCause)),
partitions=graphene.List(graphene.NonNull(graphene.String)),
)
type = graphene.Field(GrapheneDagsterType)
hasMaterializePermission = graphene.NonNull(graphene.Boolean)
hasWipePermission = graphene.NonNull(graphene.Boolean)
hasReportRunlessAssetEventPermission = graphene.NonNull(graphene.Boolean)
# the acutal checks are listed in the assetChecksOrError resolver. We use this boolean
# to show/hide the checks tab. We plan to remove this field once we always show the checks tab.
hasAssetChecks = graphene.NonNull(graphene.Boolean)
assetChecksOrError = graphene.Field(
graphene.NonNull(GrapheneAssetChecksOrError),
limit=graphene.Argument(graphene.Int),
pipeline=graphene.Argument(GraphenePipelineSelector),
)
currentAutoMaterializeEvaluationId = graphene.ID()
targetingInstigators = non_null_list(GrapheneInstigator)
class Meta:
name = "AssetNode"
def __init__(
self,
remote_node: RemoteAssetNode,
):
from dagster_graphql.implementation.fetch_assets import get_unique_asset_id
self._remote_node = check.inst_param(remote_node, "remote_node", RemoteAssetNode)
repo_scoped_node = remote_node.resolve_to_singular_repo_scoped_node()
self._asset_node_snap = repo_scoped_node.asset_node_snap
self._repository_handle = repo_scoped_node.repository_handle
self._repository_selector = self._repository_handle.to_selector()
self._remote_job = None # lazily loaded
self._node_definition_snap = None # lazily loaded
self._asset_graph_differ = None # lazily loaded
super().__init__(
id=get_unique_asset_id(
self._asset_node_snap.asset_key,
self._repository_handle.location_name,
self._repository_handle.repository_name,
),
assetKey=self._asset_node_snap.asset_key,
description=self._asset_node_snap.description,
opName=self._asset_node_snap.op_name,
opVersion=self._asset_node_snap.code_version,
groupName=self._asset_node_snap.group_name,
owners=[
self._graphene_asset_owner_from_owner_str(owner)
for owner in (self._asset_node_snap.owners or [])
],
)
def _graphene_asset_owner_from_owner_str(
self, owner_str: str
) -> Union[GrapheneUserAssetOwner, GrapheneTeamAssetOwner]:
# TODO: (prha) switch to use definition_owner_from_owner_str once we have switched the frontend
# typename checks
if is_valid_email(owner_str):
return GrapheneUserAssetOwner(email=owner_str)
else:
check.invariant(owner_str.startswith("team:"))
return GrapheneTeamAssetOwner(team=owner_str[5:])
@property
def asset_node_snap(self) -> AssetNodeSnap:
return self._asset_node_snap
def _get_remote_repo_from_context(
self, context: BaseWorkspaceRequestContext, code_location_name: str, repository_name: str
) -> Optional[RemoteRepository]:
"""Returns the ExternalRepository specified by the code location name and repository name
for the provided workspace context. If the repository doesn't exist, return None.
"""
if context.has_code_location(code_location_name):
cl = context.get_code_location(code_location_name)
if cl.has_repository(repository_name):
return cl.get_repository(repository_name)
return None
def _get_asset_graph_differ(self, graphene_info: ResolveInfo) -> Optional[AssetGraphDiffer]:
if self._asset_graph_differ is not None:
return self._asset_graph_differ
repo_selector = (
self._remote_node.repository_handle.to_selector()
if isinstance(self._remote_node, RemoteRepositoryAssetNode)
else None
)
base_deployment_asset_graph = graphene_info.context.get_base_deployment_asset_graph(
repo_selector
)
if base_deployment_asset_graph is None:
return None
if isinstance(self._remote_node, RemoteRepositoryAssetNode):
repo_handle = self._remote_node.repository_handle
repository = check.not_none(
self._get_remote_repo_from_context(
graphene_info.context,
repo_handle.location_name,
repo_handle.repository_name,
)
)
branch_asset_graph = repository.asset_graph
else:
branch_asset_graph = graphene_info.context.asset_graph
self._asset_graph_differ = AssetGraphDiffer(
branch_asset_graph=branch_asset_graph,
base_asset_graph=base_deployment_asset_graph,
)
return self._asset_graph_differ
def _job_selector(self) -> Optional[JobSelector]:
if len(self._asset_node_snap.job_names) < 1:
return None
return JobSelector(
location_name=self._repository_selector.location_name,
repository_name=self._repository_selector.repository_name,
job_name=self._asset_node_snap.job_names[0],
)
def get_remote_job(self, graphene_info: ResolveInfo) -> RemoteJob:
selector = self._job_selector()
if self._remote_job is None:
if selector is None:
check.failed("Asset must be part of a job")
self._remote_job = graphene_info.context.get_full_job(selector)
return self._remote_job
def get_node_definition_snap(
self,
graphene_info: ResolveInfo,
) -> Optional[Union[GraphDefSnap, OpDefSnap]]:
selector = self._job_selector()
if selector is None:
return None
if self._node_definition_snap is None:
node_key = check.not_none(
self._asset_node_snap.node_definition_name
# nodes serialized using an older Dagster version may not have node_definition_name
or self._asset_node_snap.graph_name
or self._asset_node_snap.op_name
)
self._node_definition_snap = graphene_info.context.get_node_def(selector, node_key)
return self._node_definition_snap
def _get_partition_keys(
self,
graphene_info: ResolveInfo,
partitions_snap: Optional[PartitionsSnap] = None,
start_idx: Optional[int] = None,
end_idx: Optional[int] = None,
) -> Sequence[str]:
# TODO: Add functionality for dynamic partitions definition
# Accepts an optional start_idx and end_idx to fetch a subset of time window partition keys
check.opt_inst_param(partitions_snap, "partitions_snap", PartitionsSnap)
check.opt_int_param(start_idx, "start_idx")
check.opt_int_param(end_idx, "end_idx")
dynamic_partitions_loader = graphene_info.context.dynamic_partitions_loader
partitions_snap = (
self._asset_node_snap.partitions if not partitions_snap else partitions_snap
)
if partitions_snap:
if isinstance(
partitions_snap,
(
StaticPartitionsSnap,
TimeWindowPartitionsSnap,
MultiPartitionsSnap,
),
):
if start_idx and end_idx and isinstance(partitions_snap, TimeWindowPartitionsSnap):
return partitions_snap.get_partitions_definition().get_partition_keys_between_indexes(
start_idx, end_idx
)
else:
return partitions_snap.get_partitions_definition().get_partition_keys(
dynamic_partitions_store=dynamic_partitions_loader
)
elif isinstance(partitions_snap, DynamicPartitionsSnap):
return dynamic_partitions_loader.get_dynamic_partitions(
partitions_def_name=partitions_snap.name
)
else:
raise DagsterInvariantViolationError(
f"Unsupported partition definition type {partitions_snap}"
)
return []
def is_multipartitioned(self) -> bool:
partitions_snap = self._asset_node_snap.partitions
return partitions_snap is not None and isinstance(partitions_snap, MultiPartitionsSnap)
def get_required_resource_keys(
self,
graphene_info: ResolveInfo,
node_def_snap: Union[GraphDefSnap, OpDefSnap],
) -> Sequence[str]:
all_keys = self.get_required_resource_keys_rec(graphene_info, node_def_snap)
return list(set(all_keys))
def get_required_resource_keys_rec(
self,
graphene_info: ResolveInfo,
node_def_snap: Union[GraphDefSnap, OpDefSnap],
) -> Sequence[str]:
if isinstance(node_def_snap, GraphDefSnap):
constituent_node_names = [
inv.node_def_name
for inv in node_def_snap.dep_structure_snapshot.node_invocation_snaps
]
job = self.get_remote_job(graphene_info)
constituent_resource_key_sets = [
self.get_required_resource_keys_rec(graphene_info, job.get_node_def_snap(name))
for name in constituent_node_names
]
return [key for res_key_set in constituent_resource_key_sets for key in res_key_set]
else:
return node_def_snap.required_resource_keys
def is_graph_backed_asset(self) -> bool:
return self.graphName is not None
@property
def is_executable(self) -> bool:
return self._asset_node_snap.is_executable
def resolve_hasMaterializePermission(
self,
graphene_info: ResolveInfo,
) -> bool:
return has_permission_for_definition(
graphene_info, Permissions.LAUNCH_PIPELINE_EXECUTION, self._remote_node
)
def resolve_hasWipePermission(
self,
graphene_info: ResolveInfo,
) -> bool:
return has_permission_for_definition(
graphene_info, Permissions.WIPE_ASSETS, self._remote_node
)
def resolve_hasReportRunlessAssetEventPermission(
self,
graphene_info: ResolveInfo,
) -> bool:
return has_permission_for_definition(
graphene_info, Permissions.REPORT_RUNLESS_ASSET_EVENTS, self._remote_node
)
def resolve_assetMaterializationUsedData(
self,
graphene_info: ResolveInfo,
timestampMillis: str,
) -> Sequence[GrapheneMaterializationUpstreamDataVersion]:
if not timestampMillis:
return []
instance = graphene_info.context.instance
asset_graph = graphene_info.context.asset_graph
asset_key = self._asset_node_snap.asset_key
event_records = instance.fetch_materializations(
AssetRecordsFilter(
asset_key=asset_key,
before_timestamp=int(timestampMillis) / 1000.0 + 1,
after_timestamp=int(timestampMillis) / 1000.0 - 1,
),
limit=1,
).records
if not event_records:
return []
if not asset_graph.has_materializable_parents(asset_key):
return []
used_data_times = graphene_info.context.data_time_resolver.get_data_time_by_key_for_record(
record=next(iter(event_records)),
)
return [
GrapheneMaterializationUpstreamDataVersion(
assetKey=used_asset_key,
downstreamAssetKey=asset_key,
timestamp=int(materialization_time.timestamp() * 1000),
)
for used_asset_key, materialization_time in used_data_times.items()
if materialization_time
]
def resolve_assetMaterializations(
self,
graphene_info: ResolveInfo,
partitions: Optional[Sequence[str]] = None,
beforeTimestampMillis: Optional[str] = None,
limit: Optional[int] = None,
) -> Sequence[GrapheneMaterializationEvent]:
try:
before_timestamp = (
int(beforeTimestampMillis) / 1000.0 if beforeTimestampMillis else None
)
except ValueError:
before_timestamp = None
if limit == 1 and not partitions and not before_timestamp:
record = AssetRecord.blocking_get(
graphene_info.context, self._asset_node_snap.asset_key
)
latest_materialization_event = (
record.asset_entry.last_materialization if record else None
)
if not latest_materialization_event:
return []
return [GrapheneMaterializationEvent(event=latest_materialization_event)]
return [
GrapheneMaterializationEvent(event=event)
for event in get_asset_materializations(
graphene_info,
self._asset_node_snap.asset_key,
partitions,
before_timestamp=before_timestamp,
limit=limit,
)
]
def resolve_assetObservations(
self,
graphene_info: ResolveInfo,
partitions: Optional[Sequence[str]] = None,
beforeTimestampMillis: Optional[str] = None,
limit: Optional[int] = None,
) -> Sequence[GrapheneObservationEvent]:
try:
before_timestamp = (
int(beforeTimestampMillis) / 1000.0 if beforeTimestampMillis else None
)
except ValueError:
before_timestamp = None
if (
graphene_info.context.instance.event_log_storage.asset_records_have_last_observation
and limit == 1
and not partitions
and not before_timestamp
):
record = AssetRecord.blocking_get(
graphene_info.context, self._asset_node_snap.asset_key
)
latest_observation_event = record.asset_entry.last_observation if record else None
if not latest_observation_event:
return []
return [GrapheneObservationEvent(event=latest_observation_event)]
return [
GrapheneObservationEvent(event=event)
for event in get_asset_observations(
graphene_info,
self._asset_node_snap.asset_key,
partitions,
before_timestamp=before_timestamp,
limit=limit,
)
]
def resolve_configField(self, graphene_info: ResolveInfo) -> Optional[GrapheneConfigTypeField]:
selector = self._job_selector()
if selector is None:
return None
node_def_snap = self.get_node_definition_snap(graphene_info)
if node_def_snap is None or node_def_snap.config_field_snap is None:
return None
def _get_config_type(key: str):
return graphene_info.context.get_config_type(selector, key)
return GrapheneConfigTypeField(
get_config_type=_get_config_type,
field_snap=node_def_snap.config_field_snap,
)
def resolve_computeKind(self, _graphene_info: ResolveInfo) -> Optional[str]:
return self._asset_node_snap.compute_kind
def resolve_changedReasons(
self, graphene_info: ResolveInfo
) -> Sequence[Any]: # Sequence[GrapheneAssetChangedReason]
asset_graph_differ = self._get_asset_graph_differ(graphene_info)
if asset_graph_differ is None:
# asset_graph_differ is None when not in a branch deployment
return []
return asset_graph_differ.get_changes_for_asset(self._asset_node_snap.asset_key)
def resolve_staleStatus(
self, graphene_info: ResolveInfo, partition: Optional[str] = None
) -> Any: # (GrapheneAssetStaleStatus)
if partition:
self._validate_partitions_existence()
return graphene_info.context.stale_status_loader.get_status(
self._asset_node_snap.asset_key, partition
)
def resolve_staleStatusByPartition(
self,
graphene_info: ResolveInfo,
partitions: Optional[Sequence[str]] = None,
) -> Sequence[Any]: # (GrapheneAssetStaleStatus)
if partitions is None:
partitions = self._get_partitions_def().get_partition_keys(
dynamic_partitions_store=graphene_info.context.dynamic_partitions_loader
)
else:
self._validate_partitions_existence()
return [
graphene_info.context.stale_status_loader.get_status(
self._asset_node_snap.asset_key, partition
)
for partition in partitions
]
def resolve_staleCauses(
self, graphene_info: ResolveInfo, partition: Optional[str] = None
) -> Sequence[GrapheneAssetStaleCause]:
if partition:
self._validate_partitions_existence()
return self._get_staleCauses(graphene_info, partition)
def resolve_staleCausesByPartition(
self,
graphene_info: ResolveInfo,
partitions: Optional[Sequence[str]] = None,
) -> Sequence[Sequence[GrapheneAssetStaleCause]]:
if partitions is None:
partitions = self._get_partitions_def().get_partition_keys(
dynamic_partitions_store=graphene_info.context.dynamic_partitions_loader
)
else:
self._validate_partitions_existence()
return [self._get_staleCauses(graphene_info, partition) for partition in partitions]
def _get_staleCauses(
self, graphene_info: ResolveInfo, partition: Optional[str] = None
) -> Sequence[GrapheneAssetStaleCause]:
causes = graphene_info.context.stale_status_loader.get_stale_root_causes(
self._asset_node_snap.asset_key, partition
)
return [
GrapheneAssetStaleCause(
GrapheneAssetKey(path=cause.asset_key.path),
cause.partition_key,
cause.category,
cause.reason,
(
GrapheneAssetKey(path=cause.dependency.asset_key.path)
if cause.dependency
else None
),
cause.dependency_partition_key,
)
for cause in causes
]
def resolve_dataVersion(
self, graphene_info: ResolveInfo, partition: Optional[str] = None
) -> Optional[str]:
if partition:
self._validate_partitions_existence()
version = graphene_info.context.stale_status_loader.get_current_data_version(
self._asset_node_snap.asset_key, partition
)
return None if version == NULL_DATA_VERSION else version.value
def resolve_dataVersionByPartition(
self, graphene_info: ResolveInfo, partitions: Optional[Sequence[str]] = None
) -> Sequence[Optional[str]]:
if partitions is None:
partitions = self._get_partitions_def().get_partition_keys(
dynamic_partitions_store=graphene_info.context.dynamic_partitions_loader
)
else:
self._validate_partitions_existence()
data_versions = [
graphene_info.context.stale_status_loader.get_current_data_version(
self._asset_node_snap.asset_key, partition
)
for partition in partitions
]
return [
None if version == NULL_DATA_VERSION else version.value for version in data_versions
]
def resolve_dependedBy(self, graphene_info: ResolveInfo) -> list[GrapheneAssetDependency]:
if not self._remote_node.child_keys:
return []
return [
GrapheneAssetDependency(
asset_key=asset_key,
)
for asset_key in self._remote_node.child_keys
]
def resolve_dependedByKeys(self, _graphene_info: ResolveInfo) -> Sequence[GrapheneAssetKey]:
return [GrapheneAssetKey(path=key.path) for key in self._remote_node.child_keys]
def resolve_dependencyKeys(self, _graphene_info: ResolveInfo) -> Sequence[GrapheneAssetKey]:
return [
GrapheneAssetKey(path=dep.parent_asset_key.path)
for dep in self._asset_node_snap.parent_edges
]
def resolve_dependencies(self, graphene_info: ResolveInfo) -> Sequence[GrapheneAssetDependency]:
if not self._remote_node.parent_keys:
return []
return [
GrapheneAssetDependency(
asset_key=key,
partition_mapping=self._remote_node.partition_mappings.get(key),
)
for key in self._remote_node.parent_keys
]
def resolve_freshnessInfo(
self, graphene_info: ResolveInfo
) -> Optional[GrapheneAssetFreshnessInfo]:
if self._asset_node_snap.legacy_freshness_policy:
return get_freshness_info(
asset_key=self._asset_node_snap.asset_key,
data_time_resolver=graphene_info.context.data_time_resolver,
)
return None
def resolve_freshnessPolicy(
self, _graphene_info: ResolveInfo
) -> Optional[GrapheneFreshnessPolicy]:
if self._asset_node_snap.legacy_freshness_policy:
return GrapheneFreshnessPolicy(self._asset_node_snap.legacy_freshness_policy)
return None
async def resolve_freshnessStatusInfo(
self, graphene_info: ResolveInfo
) -> Optional[GrapheneFreshnessStatusInfo]:
from dagster_graphql.schema.asset_health import GrapheneAssetHealthFreshnessMeta
if not self._asset_node_snap.freshness_policy:
return None
freshness_status, freshness_status_metadata = await get_freshness_status_and_metadata(
graphene_info.context, self._asset_node_snap.asset_key
)
return GrapheneFreshnessStatusInfo(
freshnessStatus=freshness_status,
freshnessStatusMetadata=GrapheneAssetHealthFreshnessMeta(
lastMaterializedTimestamp=freshness_status_metadata.last_materialized_timestamp
)
if freshness_status_metadata
else None,
)
def resolve_internalFreshnessPolicy(
self, graphene_info: ResolveInfo
) -> Optional[GrapheneInternalFreshnessPolicy]:
if self._asset_node_snap.freshness_policy:
return GrapheneInternalFreshnessPolicy.from_policy(
self._asset_node_snap.freshness_policy
)
return None
def resolve_autoMaterializePolicy(
self, _graphene_info: ResolveInfo
) -> Optional[GrapheneAutoMaterializePolicy]:
if self._asset_node_snap.auto_materialize_policy:
return GrapheneAutoMaterializePolicy(self._asset_node_snap.auto_materialize_policy)
return None
def resolve_automationCondition(
self, _graphene_info: ResolveInfo
) -> Optional[GrapheneAutomationCondition]:
automation_condition = (
self._asset_node_snap.automation_condition_snapshot
or self._asset_node_snap.automation_condition
)
if automation_condition:
return GrapheneAutomationCondition(
# we only store one of automation_condition or automation_condition_snapshot
automation_condition
if isinstance(automation_condition, AutomationConditionSnapshot)
else automation_condition.get_snapshot()
)
return None
def resolve_targetingInstigators(self, graphene_info: ResolveInfo) -> Sequence[GrapheneSensor]:
if isinstance(self._remote_node, RemoteWorkspaceAssetNode):
# global nodes have saved references to their targeting instigators
schedules = [
schedule
for schedule_selector in self._remote_node.get_targeting_schedule_selectors()
if (schedule := graphene_info.context.get_schedule(schedule_selector)) is not None
]
sensors = [
sensor
for sensor_selector in self._remote_node.get_targeting_sensor_selectors()
if (sensor := graphene_info.context.get_sensor(sensor_selector)) is not None
]
else:
# fallback to using the repository
repo = graphene_info.context.get_repository(self._repository_selector)
schedules = repo.get_schedules_targeting(self._asset_node_snap.asset_key)
sensors = repo.get_sensors_targeting(self._asset_node_snap.asset_key)
results = []
for sensor in sensors:
sensor_state = graphene_info.context.instance.get_instigator_state(
sensor.get_remote_origin_id(),
sensor.selector_id,
)
results.append(
GrapheneSensor(
sensor,
sensor_state,
)
)
for schedule in schedules:
schedule_state = graphene_info.context.instance.get_instigator_state(
schedule.get_remote_origin_id(),
schedule.selector_id,
)
results.append(
GrapheneSchedule(
schedule,
schedule_state,
)
)
return results
def _get_auto_materialize_remote_sensor(
self, graphene_info: ResolveInfo
) -> Optional[RemoteSensor]:
repo = graphene_info.context.get_repository(self._repository_selector)
asset_graph = repo.asset_graph
asset_key = self._asset_node_snap.asset_key
matching_sensors = [
sensor
for sensor in repo.get_sensors()
if sensor.sensor_type == SensorType.AUTO_MATERIALIZE
and asset_key in check.not_none(sensor.asset_selection).resolve(asset_graph)
]
check.invariant(
len(matching_sensors) <= 1,
f"More than one automation policy sensor targeting asset key {asset_key}",
)
if not matching_sensors:
return None
return matching_sensors[0]
def resolve_currentAutoMaterializeEvaluationId(self, graphene_info: ResolveInfo):
from dagster._daemon.asset_daemon import get_current_evaluation_id
instance = graphene_info.context.instance
if instance.auto_materialize_use_sensors:
sensor = self._get_auto_materialize_remote_sensor(graphene_info)
if not sensor:
return None
return get_current_evaluation_id(
graphene_info.context.instance, sensor.get_remote_origin()
)
else:
return get_current_evaluation_id(graphene_info.context.instance, None)
def resolve_lastAutoMaterializationEvaluationRecord(
self, graphene_info: ResolveInfo, asOfEvaluationId: Optional[str] = None
):
schedule_storage = check.not_none(graphene_info.context.instance.schedule_storage)
evaluation_records = schedule_storage.get_auto_materialize_asset_evaluations(
key=self._asset_node_snap.asset_key,
limit=1,
cursor=int(asOfEvaluationId) + 1 if asOfEvaluationId else None,
)
if not evaluation_records:
return None
return GrapheneAutoMaterializeAssetEvaluationRecord(
record=evaluation_records[0],
)
def resolve_backfillPolicy(
self, _graphene_info: ResolveInfo
) -> Optional[GrapheneBackfillPolicy]:
if self._asset_node_snap.backfill_policy:
return GrapheneBackfillPolicy(self._asset_node_snap.backfill_policy)
return None
def resolve_jobNames(self, _graphene_info: ResolveInfo) -> Sequence[str]:
return self._asset_node_snap.job_names
def resolve_jobs(self, graphene_info: ResolveInfo) -> Sequence[GraphenePipeline]:
job_names = self._asset_node_snap.job_names or []
repo = graphene_info.context.get_repository(self._repository_selector)
return [
GraphenePipeline(repo.get_full_job(job_name))
for job_name in job_names
if repo.has_job(job_name)
]
def resolve_isPartitioned(self, _graphene_info: ResolveInfo) -> bool:
return self._asset_node_snap.partitions is not None
def resolve_isMaterializable(self, _graphene_info: ResolveInfo) -> bool:
return self._asset_node_snap.is_materializable
def resolve_isObservable(self, _graphene_info: ResolveInfo) -> bool:
return self._asset_node_snap.is_observable
def resolve_isExecutable(self, _graphene_info: ResolveInfo) -> bool:
return self._asset_node_snap.is_executable
def resolve_latestMaterializationByPartition(
self,
graphene_info: ResolveInfo,
partitions: Optional[Sequence[str]] = None,
) -> Sequence[Optional[GrapheneMaterializationEvent]]:
latest_storage_ids = sorted(
(
graphene_info.context.instance.event_log_storage.get_latest_storage_id_by_partition(
self._asset_node_snap.asset_key,
DagsterEventType.ASSET_MATERIALIZATION,
set(partitions) if partitions else None,
)
).values()
)
events_for_partitions = get_asset_materializations(
graphene_info,
asset_key=self._asset_node_snap.asset_key,
storage_ids=latest_storage_ids,
)
latest_materialization_by_partition = {
event.dagster_event.step_materialization_data.materialization.partition: event
for event in events_for_partitions
if event.dagster_event
}
# return materializations in the same order as the provided partitions, None if
# materialization does not exist
partitions = self._get_partition_keys(graphene_info) if partitions is None else partitions
ordered_materializations = [
latest_materialization_by_partition.get(partition) for partition in partitions
]
return [
GrapheneMaterializationEvent(event=event) if event else None
for event in ordered_materializations
]
def resolve_latestRunForPartition(
self,
graphene_info: ResolveInfo,
partition: str,
) -> Optional[GrapheneRun]:
planned_info = graphene_info.context.instance.get_latest_planned_materialization_info(
asset_key=self._asset_node_snap.asset_key, partition=partition
)
if not planned_info:
return None
run_record = graphene_info.context.instance.get_run_record_by_id(planned_info.run_id)
return GrapheneRun(run_record) if run_record else None
async def resolve_assetPartitionStatuses(
self, graphene_info: ResolveInfo
) -> Union[
"GrapheneTimePartitionStatuses",
"GrapheneDefaultPartitionStatuses",
"GrapheneMultiPartitionStatuses",
]:
partitions_def = (
self._asset_node_snap.partitions.get_partitions_definition()
if self._asset_node_snap.partitions
else None
)
(
materialized_partition_subset,
failed_partition_subset,
in_progress_subset,
) = await regenerate_and_check_partition_subsets(
graphene_info.context,
self._asset_node_snap,
graphene_info.context.dynamic_partitions_loader,
)
return build_partition_statuses(
graphene_info.context.dynamic_partitions_loader,
materialized_partition_subset,
failed_partition_subset,
in_progress_subset,
partitions_def,
)
async def resolve_partitionStats(
self, graphene_info: ResolveInfo
) -> Optional[GraphenePartitionStats]:
partitions_snap = self._asset_node_snap.partitions
if partitions_snap:
with partition_loading_context(
dynamic_partitions_store=graphene_info.context.dynamic_partitions_loader
):
(
materialized_partition_subset,
failed_partition_subset,
in_progress_subset,
) = await regenerate_and_check_partition_subsets(
graphene_info.context,
self._asset_node_snap,
graphene_info.context.dynamic_partitions_loader,
)
if (
materialized_partition_subset is None
or failed_partition_subset is None
or in_progress_subset is None
):
check.failed("Expected partitions subset for a partitioned asset")
failed_or_in_progress_subset = failed_partition_subset | in_progress_subset
failed_and_not_in_progress_subset = failed_partition_subset - in_progress_subset
materialized_and_not_failed_or_in_progress_subset = (
materialized_partition_subset - failed_or_in_progress_subset
)
return GraphenePartitionStats(
numMaterialized=len(materialized_and_not_failed_or_in_progress_subset),
numPartitions=partitions_snap.get_partitions_definition().get_num_partitions(),
numFailed=len(failed_and_not_in_progress_subset),
numMaterializing=len(in_progress_subset),
)
else:
return None
def resolve_metadata_entries(
self, _graphene_info: ResolveInfo
) -> Sequence[GrapheneMetadataEntry]:
return list(iterate_metadata_entries(self._asset_node_snap.metadata))
def resolve_isAutoCreatedStub(self, _graphene_info: ResolveInfo) -> bool:
return (
self._asset_node_snap.metadata.get(SYSTEM_METADATA_KEY_AUTO_CREATED_STUB_ASSET)
is not None
)
def resolve_tags(self, _graphene_info: ResolveInfo) -> Sequence[GrapheneDefinitionTag]:
return [
GrapheneDefinitionTag(key, value)
for key, value in (self._asset_node_snap.tags or {}).items()
]
def resolve_kinds(self, _graphene_info: ResolveInfo) -> Sequence[str]:
if self._asset_node_snap.compute_kind:
return [self._asset_node_snap.compute_kind]
return [
key[len(KIND_PREFIX) :]
for key in (self._asset_node_snap.tags or {}).keys()
if key.startswith(KIND_PREFIX)
]
def resolve_op(
self, graphene_info: ResolveInfo
) -> Optional[Union[GrapheneSolidDefinition, GrapheneCompositeSolidDefinition]]:
if not self.is_executable:
return None
job = self.get_remote_job(graphene_info)
node_def_snap = self.get_node_definition_snap(graphene_info)
if node_def_snap is None:
return None
if isinstance(node_def_snap, OpDefSnap):
return GrapheneSolidDefinition(job, node_def_snap.name)
if isinstance(node_def_snap, GraphDefSnap):
return GrapheneCompositeSolidDefinition(job, node_def_snap.name)
check.failed(f"Unknown solid definition type {type(node_def_snap)}")
def resolve_opNames(self, _graphene_info: ResolveInfo) -> Sequence[str]:
return self._asset_node_snap.op_names or []
def resolve_graphName(self, _graphene_info: ResolveInfo) -> Optional[str]:
return self._asset_node_snap.graph_name
def resolve_partitionKeysByDimension(
self,
graphene_info: ResolveInfo,
startIdx: Optional[int] = None,
endIdx: Optional[int] = None,
) -> Sequence[GrapheneDimensionPartitionKeys]:
# Accepts startIdx and endIdx arguments. This will be used to select a range of
# time partitions. StartIdx is inclusive, endIdx is exclusive.
# For non time partition definitions, these arguments will be ignored
# and the full list of partition keys will be returned.
if not self._asset_node_snap.partitions:
return []
if self.is_multipartitioned():
return [
GrapheneDimensionPartitionKeys(
name=dimension.name,
partition_keys=self._get_partition_keys(
graphene_info,
dimension.partitions,
startIdx,
endIdx,
),
type=GraphenePartitionDefinitionType.from_partition_def_data(
dimension.partitions
),
)
for dimension in cast(
"MultiPartitionsSnap",
self._asset_node_snap.partitions,
).partition_dimensions
]
return [
GrapheneDimensionPartitionKeys(
name="default",
type=GraphenePartitionDefinitionType.from_partition_def_data(
self._asset_node_snap.partitions
),
partition_keys=self._get_partition_keys(
graphene_info=graphene_info, start_idx=startIdx, end_idx=endIdx
),
)
]
def resolve_partitionKeys(self, graphene_info: ResolveInfo) -> Sequence[str]:
return self._get_partition_keys(graphene_info)
def resolve_partitionKeyConnection(
self,
graphene_info: ResolveInfo,
limit: int,
ascending: bool,
cursor: Optional[str] = None,
) -> Optional[GraphenePartitionKeyConnection]:
if not self._remote_node.is_partitioned:
return None
partitions_def = self._get_partitions_def()
context = PartitionLoadingContext(
temporal_context=TemporalContext(
effective_dt=get_current_datetime(),
last_event_id=graphene_info.context.instance.event_log_storage.get_maximum_record_id(),
),
dynamic_partitions_store=graphene_info.context.dynamic_partitions_loader,
)
results = partitions_def.get_paginated_partition_keys(
context=context,
limit=limit,
ascending=ascending,
cursor=cursor,
)
return GraphenePartitionKeyConnection(
results=results.results,
cursor=results.cursor,
hasMore=results.has_more,
)
def resolve_partitionDefinition(
self, _graphene_info: ResolveInfo
) -> Optional[GraphenePartitionDefinition]:
partitions_snap = self._asset_node_snap.partitions
if partitions_snap:
return GraphenePartitionDefinition(partitions_snap)
return None
def resolve_pools(self, _graphene_info: ResolveInfo) -> Sequence[str]:
return sorted([pool for pool in self._asset_node_snap.pools or set()])
def resolve_repository(self, graphene_info: ResolveInfo) -> "GrapheneRepository":
return external.GrapheneRepository(self._repository_handle)
def resolve_required_resources(
self, graphene_info: ResolveInfo
) -> Sequence[GrapheneResourceRequirement]:
if not self.is_executable:
return []
node_def_snap = self.get_node_definition_snap(graphene_info)
if node_def_snap is None:
return []
all_unique_keys = self.get_required_resource_keys(graphene_info, node_def_snap)
return [GrapheneResourceRequirement(key) for key in all_unique_keys]
def resolve_type(
self, graphene_info: ResolveInfo
) -> Optional[
Union[
"GrapheneListDagsterType", "GrapheneNullableDagsterType", "GrapheneRegularDagsterType"
]
]:
selector = self._job_selector()
node_def_snap = self.get_node_definition_snap(graphene_info)
if selector is None or node_def_snap is None:
return None
def _get_dagster_type(key: str):
return graphene_info.context.get_dagster_type(selector, key)
def _get_config_type(key: str):
return graphene_info.context.get_config_type(selector, key)
output_name = self._asset_node_snap.output_name
if output_name:
for output_def in node_def_snap.output_def_snaps:
if output_def.name == output_name:
return to_dagster_type(
get_dagster_type=_get_dagster_type,
get_config_type=_get_config_type,
dagster_type_key=output_def.dagster_type_key,
)
return None
def _get_partitions_def(self) -> PartitionsDefinition:
if not self._asset_node_snap.partitions:
check.failed("Asset node has no partitions definition")
return self._asset_node_snap.partitions.get_partitions_definition()
def _validate_partitions_existence(self) -> None:
if not self._asset_node_snap.partitions:
check.failed("Asset node has no partitions definition")
def resolve_hasAssetChecks(self, graphene_info: ResolveInfo) -> bool:
return bool(self._remote_node.check_keys)
def resolve_assetChecksOrError(
self,
graphene_info: ResolveInfo,
limit=None,
pipeline: Optional[GraphenePipelineSelector] = None,
) -> AssetChecksOrErrorUnion:
remote_check_nodes = graphene_info.context.asset_graph.get_checks_for_asset(
self._asset_node_snap.asset_key
)
if not remote_check_nodes:
return GrapheneAssetChecks(checks=[])
asset_check_support = graphene_info.context.instance.get_asset_check_support()
if asset_check_support == AssetCheckInstanceSupport.NEEDS_MIGRATION:
return GrapheneAssetCheckNeedsMigrationError(
message="Asset checks require an instance migration. Run `dagster instance migrate`."
)
elif asset_check_support == AssetCheckInstanceSupport.NEEDS_AGENT_UPGRADE:
return GrapheneAssetCheckNeedsAgentUpgradeError(
"Asset checks require an agent upgrade to 1.5.0 or greater."
)
else:
check.invariant(
asset_check_support == AssetCheckInstanceSupport.SUPPORTED,
f"Unexpected asset check support status {asset_check_support}",
)
library_versions = graphene_info.context.get_dagster_library_versions(
self._repository_handle.location_name
)
code_location_version = (library_versions or {}).get("dagster")
if code_location_version and version.parse(code_location_version) < version.parse("1.5"):
return GrapheneAssetCheckNeedsUserCodeUpgrade(
message=(
"Asset checks require dagster>=1.5. Upgrade your dagster"
" version for this code location."
)
)
if pipeline:
remote_check_nodes = [
node
for node in remote_check_nodes
if node.handle.location_name == pipeline.repositoryLocationName
and node.handle.repository_name == pipeline.repositoryName
and pipeline.pipelineName in node.asset_check.job_names
]
if limit:
remote_check_nodes = remote_check_nodes[:limit]
return GrapheneAssetChecks(
checks=[
GrapheneAssetCheck(remote_check_node) for remote_check_node in remote_check_nodes
]
)
|
GrapheneAssetNode
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.