index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
729,859
touca._runner
workflow
Registers the decorated function as a regression test workflow to be executed, once, for each test case. The following example demonstrates how to use this decorator:: @touca.workflow def test_students(testcase: str): student = find_student(testcase) touca.assume("username", student.username) touca.check("fullname", student.fullname) touca.check("birth_date", student.dob) touca.check("gpa", calculate_gpa(student.courses))
def workflow(method=None, testcases=None): """ Registers the decorated function as a regression test workflow to be executed, once, for each test case. The following example demonstrates how to use this decorator:: @touca.workflow def test_students(testcase: str): student = find_student(testcase) touca.assume("username", student.username) touca.check("fullname", student.fullname) touca.check("birth_date", student.dob) touca.check("gpa", calculate_gpa(student.courses)) """ from functools import wraps from inspect import isgenerator, isgeneratorfunction @wraps(method) def wrapper(wrapped_method): tcs = None if type(testcases) is list: tcs = testcases elif isgenerator(testcases): tcs = list(testcases) elif isgeneratorfunction(testcases): tcs = list(testcases()) options = {"callback": wrapped_method, "suite": wrapped_method.__name__} if tcs is not None: options["testcases"] = tcs _workflows.append(options) return wrapper(method) if method else wrapper
(method=None, testcases=None)
729,861
marshmallow_enum
EnumField
null
class EnumField(Field): VALUE = LoadDumpOptions.value NAME = LoadDumpOptions.name default_error_messages = { 'by_name': 'Invalid enum member {input}', 'by_value': 'Invalid enum value {input}', 'must_be_string': 'Enum name must be string' } def __init__( self, enum, by_value=False, load_by=None, dump_by=None, error='', *args, **kwargs ): self.enum = enum self.by_value = by_value if error and any(old in error for old in ('name}', 'value}', 'choices}')): warnings.warn( "'name', 'value', and 'choices' fail inputs are deprecated," "use input, names and values instead", DeprecationWarning, stacklevel=2 ) self.error = error if load_by is None: load_by = LoadDumpOptions.value if by_value else LoadDumpOptions.name if not isinstance(load_by, Enum) or load_by not in LoadDumpOptions: raise ValueError( 'Invalid selection for load_by must be EnumField.VALUE or EnumField.NAME, got {}'. format(load_by) ) if dump_by is None: dump_by = LoadDumpOptions.value if by_value else LoadDumpOptions.name if not isinstance(dump_by, Enum) or dump_by not in LoadDumpOptions: raise ValueError( 'Invalid selection for load_by must be EnumField.VALUE or EnumField.NAME, got {}'. format(dump_by) ) self.load_by = load_by self.dump_by = dump_by super(EnumField, self).__init__(*args, **kwargs) def _serialize(self, value, attr, obj): if value is None: return None elif self.dump_by == LoadDumpOptions.value: return value.value else: return value.name def _deserialize(self, value, attr, data, **kwargs): if value is None: return None elif self.load_by == LoadDumpOptions.value: return self._deserialize_by_value(value, attr, data) else: return self._deserialize_by_name(value, attr, data) def _deserialize_by_value(self, value, attr, data): try: return self.enum(value) except ValueError: self.fail('by_value', input=value, value=value) def _deserialize_by_name(self, value, attr, data): if not isinstance(value, string_types): self.fail('must_be_string', input=value, name=value) try: return getattr(self.enum, value) except AttributeError: self.fail('by_name', input=value, name=value) def fail(self, key, **kwargs): kwargs['values'] = ', '.join([text_type(mem.value) for mem in self.enum]) kwargs['names'] = ', '.join([mem.name for mem in self.enum]) if self.error: if self.by_value: kwargs['choices'] = kwargs['values'] else: kwargs['choices'] = kwargs['names'] msg = self.error.format(**kwargs) raise ValidationError(msg) else: super(EnumField, self).fail(key, **kwargs)
(enum, by_value=False, load_by=None, dump_by=None, error='', *args, **kwargs)
729,863
marshmallow_enum
__init__
null
def __init__( self, enum, by_value=False, load_by=None, dump_by=None, error='', *args, **kwargs ): self.enum = enum self.by_value = by_value if error and any(old in error for old in ('name}', 'value}', 'choices}')): warnings.warn( "'name', 'value', and 'choices' fail inputs are deprecated," "use input, names and values instead", DeprecationWarning, stacklevel=2 ) self.error = error if load_by is None: load_by = LoadDumpOptions.value if by_value else LoadDumpOptions.name if not isinstance(load_by, Enum) or load_by not in LoadDumpOptions: raise ValueError( 'Invalid selection for load_by must be EnumField.VALUE or EnumField.NAME, got {}'. format(load_by) ) if dump_by is None: dump_by = LoadDumpOptions.value if by_value else LoadDumpOptions.name if not isinstance(dump_by, Enum) or dump_by not in LoadDumpOptions: raise ValueError( 'Invalid selection for load_by must be EnumField.VALUE or EnumField.NAME, got {}'. format(dump_by) ) self.load_by = load_by self.dump_by = dump_by super(EnumField, self).__init__(*args, **kwargs)
(self, enum, by_value=False, load_by=None, dump_by=None, error='', *args, **kwargs)
729,866
marshmallow_enum
_deserialize
null
def _deserialize(self, value, attr, data, **kwargs): if value is None: return None elif self.load_by == LoadDumpOptions.value: return self._deserialize_by_value(value, attr, data) else: return self._deserialize_by_name(value, attr, data)
(self, value, attr, data, **kwargs)
729,867
marshmallow_enum
_deserialize_by_name
null
def _deserialize_by_name(self, value, attr, data): if not isinstance(value, string_types): self.fail('must_be_string', input=value, name=value) try: return getattr(self.enum, value) except AttributeError: self.fail('by_name', input=value, name=value)
(self, value, attr, data)
729,868
marshmallow_enum
_deserialize_by_value
null
def _deserialize_by_value(self, value, attr, data): try: return self.enum(value) except ValueError: self.fail('by_value', input=value, value=value)
(self, value, attr, data)
729,869
marshmallow_enum
_serialize
null
def _serialize(self, value, attr, obj): if value is None: return None elif self.dump_by == LoadDumpOptions.value: return value.value else: return value.name
(self, value, attr, obj)
729,873
marshmallow_enum
fail
null
def fail(self, key, **kwargs): kwargs['values'] = ', '.join([text_type(mem.value) for mem in self.enum]) kwargs['names'] = ', '.join([mem.name for mem in self.enum]) if self.error: if self.by_value: kwargs['choices'] = kwargs['values'] else: kwargs['choices'] = kwargs['names'] msg = self.error.format(**kwargs) raise ValidationError(msg) else: super(EnumField, self).fail(key, **kwargs)
(self, key, **kwargs)
729,877
marshmallow.fields
Field
Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned. :param dump_default: If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable. :param load_default: Default deserialization value for the field if the field is not found in the input data. May be a value or a callable. :param data_key: The name of the dict key in the external representation, i.e. the input of `load` and the output of `dump`. If `None`, the key will match the name of the field. :param attribute: The name of the key/attribute in the internal representation, i.e. the output of `load` and the input of `dump`. If `None`, the key/attribute will match the name of the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute, or using keys/attributes that are invalid variable names, unsuitable for field names. In most cases, you should use ``data_key`` instead. :param validate: Validator or collection of validators that are called during deserialization. Validator takes a field's input value as its only parameter and returns a boolean. If it returns `False`, an :exc:`ValidationError` is raised. :param required: Raise a :exc:`ValidationError` if the field value is not supplied during deserialization. :param allow_none: Set this to `True` if `None` should be considered a valid value during validation/deserialization. If ``load_default=None`` and ``allow_none`` is unset, will default to ``True``. Otherwise, the default is ``False``. :param load_only: If `True` skip this field during serialization, otherwise its value will be present in the serialized data. :param dump_only: If `True` skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as "read-only". :param dict error_messages: Overrides for `Field.default_error_messages`. :param metadata: Extra information to be stored as field metadata. .. versionchanged:: 2.0.0 Removed `error` parameter. Use ``error_messages`` instead. .. versionchanged:: 2.0.0 Added `allow_none` parameter, which makes validation/deserialization of `None` consistent across fields. .. versionchanged:: 2.0.0 Added `load_only` and `dump_only` parameters, which allow field skipping during the (de)serialization process. .. versionchanged:: 2.0.0 Added `missing` parameter, which indicates the value for a field if the field is not found during deserialization. .. versionchanged:: 2.0.0 ``default`` value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output. .. versionchanged:: 3.0.0b8 Add ``data_key`` parameter for the specifying the key in the input and output data. This parameter replaced both ``load_from`` and ``dump_to``.
class Field(FieldABC): """Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized or deserialized. On error, the name of the field will be returned. :param dump_default: If set, this value will be used during serialization if the input value is missing. If not set, the field will be excluded from the serialized output if the input value is missing. May be a value or a callable. :param load_default: Default deserialization value for the field if the field is not found in the input data. May be a value or a callable. :param data_key: The name of the dict key in the external representation, i.e. the input of `load` and the output of `dump`. If `None`, the key will match the name of the field. :param attribute: The name of the key/attribute in the internal representation, i.e. the output of `load` and the input of `dump`. If `None`, the key/attribute will match the name of the field. Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute, or using keys/attributes that are invalid variable names, unsuitable for field names. In most cases, you should use ``data_key`` instead. :param validate: Validator or collection of validators that are called during deserialization. Validator takes a field's input value as its only parameter and returns a boolean. If it returns `False`, an :exc:`ValidationError` is raised. :param required: Raise a :exc:`ValidationError` if the field value is not supplied during deserialization. :param allow_none: Set this to `True` if `None` should be considered a valid value during validation/deserialization. If ``load_default=None`` and ``allow_none`` is unset, will default to ``True``. Otherwise, the default is ``False``. :param load_only: If `True` skip this field during serialization, otherwise its value will be present in the serialized data. :param dump_only: If `True` skip this field during deserialization, otherwise its value will be present in the deserialized object. In the context of an HTTP API, this effectively marks the field as "read-only". :param dict error_messages: Overrides for `Field.default_error_messages`. :param metadata: Extra information to be stored as field metadata. .. versionchanged:: 2.0.0 Removed `error` parameter. Use ``error_messages`` instead. .. versionchanged:: 2.0.0 Added `allow_none` parameter, which makes validation/deserialization of `None` consistent across fields. .. versionchanged:: 2.0.0 Added `load_only` and `dump_only` parameters, which allow field skipping during the (de)serialization process. .. versionchanged:: 2.0.0 Added `missing` parameter, which indicates the value for a field if the field is not found during deserialization. .. versionchanged:: 2.0.0 ``default`` value is only used if explicitly set. Otherwise, missing values inputs are excluded from serialized output. .. versionchanged:: 3.0.0b8 Add ``data_key`` parameter for the specifying the key in the input and output data. This parameter replaced both ``load_from`` and ``dump_to``. """ # Some fields, such as Method fields and Function fields, are not expected # to exist as attributes on the objects to serialize. Set this to False # for those fields _CHECK_ATTRIBUTE = True #: Default error messages for various kinds of errors. The keys in this dictionary #: are passed to `Field.make_error`. The values are error messages passed to #: :exc:`marshmallow.exceptions.ValidationError`. default_error_messages = { "required": "Missing data for required field.", "null": "Field may not be null.", "validator_failed": "Invalid value.", } def __init__( self, *, load_default: typing.Any = missing_, missing: typing.Any = missing_, dump_default: typing.Any = missing_, default: typing.Any = missing_, data_key: str | None = None, attribute: str | None = None, validate: ( None | typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]] ) = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: typing.Mapping[str, typing.Any] | None = None, **additional_metadata, ) -> None: # handle deprecated `default` and `missing` parameters if default is not missing_: warnings.warn( "The 'default' argument to fields is deprecated. " "Use 'dump_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) if dump_default is missing_: dump_default = default if missing is not missing_: warnings.warn( "The 'missing' argument to fields is deprecated. " "Use 'load_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) if load_default is missing_: load_default = missing self.dump_default = dump_default self.load_default = load_default self.attribute = attribute self.data_key = data_key self.validate = validate if validate is None: self.validators = [] elif callable(validate): self.validators = [validate] elif utils.is_iterable_but_not_string(validate): self.validators = list(validate) else: raise ValueError( "The 'validate' parameter must be a callable " "or a collection of callables." ) # If allow_none is None and load_default is None # None should be considered valid by default self.allow_none = load_default is None if allow_none is None else allow_none self.load_only = load_only self.dump_only = dump_only if required is True and load_default is not missing_: raise ValueError("'load_default' must not be set for required fields.") self.required = required metadata = metadata or {} self.metadata = {**metadata, **additional_metadata} if additional_metadata: warnings.warn( "Passing field metadata as keyword arguments is deprecated. Use the " "explicit `metadata=...` argument instead. " f"Additional metadata: {additional_metadata}", RemovedInMarshmallow4Warning, stacklevel=2, ) # Collect default error message from self and parent classes messages = {} # type: dict[str, str] for cls in reversed(self.__class__.__mro__): messages.update(getattr(cls, "default_error_messages", {})) messages.update(error_messages or {}) self.error_messages = messages def __repr__(self) -> str: return ( f"<fields.{self.__class__.__name__}(dump_default={self.dump_default!r}, " f"attribute={self.attribute!r}, " f"validate={self.validate}, required={self.required}, " f"load_only={self.load_only}, dump_only={self.dump_only}, " f"load_default={self.load_default}, allow_none={self.allow_none}, " f"error_messages={self.error_messages})>" ) def __deepcopy__(self, memo): return copy.copy(self) def get_value(self, obj, attr, accessor=None, default=missing_): """Return the value for a given key from an object. :param object obj: The object to get the value from. :param str attr: The attribute/key in `obj` to get the value from. :param callable accessor: A callable used to retrieve the value of `attr` from the object `obj`. Defaults to `marshmallow.utils.get_value`. """ accessor_func = accessor or utils.get_value check_key = attr if self.attribute is None else self.attribute return accessor_func(obj, check_key, default) def _validate(self, value): """Perform validation on ``value``. Raise a :exc:`ValidationError` if validation does not succeed. """ self._validate_all(value) @property def _validate_all(self): return And(*self.validators, error=self.error_messages["validator_failed"]) def make_error(self, key: str, **kwargs) -> ValidationError: """Helper method to make a `ValidationError` with an error message from ``self.error_messages``. """ try: msg = self.error_messages[key] except KeyError as error: class_name = self.__class__.__name__ message = ( f"ValidationError raised by `{class_name}`, but error key `{key}` does " "not exist in the `error_messages` dictionary." ) raise AssertionError(message) from error if isinstance(msg, (str, bytes)): msg = msg.format(**kwargs) return ValidationError(msg) def fail(self, key: str, **kwargs): """Helper method that raises a `ValidationError` with an error message from ``self.error_messages``. .. deprecated:: 3.0.0 Use `make_error <marshmallow.fields.Field.make_error>` instead. """ warnings.warn( f'`Field.fail` is deprecated. Use `raise self.make_error("{key}", ...)` instead.', RemovedInMarshmallow4Warning, stacklevel=2, ) raise self.make_error(key=key, **kwargs) def _validate_missing(self, value): """Validate missing values. Raise a :exc:`ValidationError` if `value` should be considered missing. """ if value is missing_ and self.required: raise self.make_error("required") if value is None and not self.allow_none: raise self.make_error("null") def serialize( self, attr: str, obj: typing.Any, accessor: typing.Callable[[typing.Any, str, typing.Any], typing.Any] | None = None, **kwargs, ): """Pulls the value for the given key from the object, applies the field's formatting and returns the result. :param attr: The attribute/key to get from the object. :param obj: The object to access the attribute/key from. :param accessor: Function used to access values from ``obj``. :param kwargs: Field-specific keyword arguments. """ if self._CHECK_ATTRIBUTE: value = self.get_value(obj, attr, accessor=accessor) if value is missing_: default = self.dump_default value = default() if callable(default) else default if value is missing_: return value else: value = None return self._serialize(value, attr, obj, **kwargs) def deserialize( self, value: typing.Any, attr: str | None = None, data: typing.Mapping[str, typing.Any] | None = None, **kwargs, ): """Deserialize ``value``. :param value: The value to deserialize. :param attr: The attribute/key in `data` to deserialize. :param data: The raw input data passed to `Schema.load`. :param kwargs: Field-specific keyword arguments. :raise ValidationError: If an invalid value is passed or if a required value is missing. """ # Validate required fields, deserialize, then validate # deserialized value self._validate_missing(value) if value is missing_: _miss = self.load_default return _miss() if callable(_miss) else _miss if self.allow_none and value is None: return None output = self._deserialize(value, attr, data, **kwargs) self._validate(output) return output # Methods for concrete classes to override. def _bind_to_schema(self, field_name, schema): """Update field with values from its parent schema. Called by :meth:`Schema._bind_field <marshmallow.Schema._bind_field>`. :param str field_name: Field name set in schema. :param Schema|Field schema: Parent object. """ self.parent = self.parent or schema self.name = self.name or field_name self.root = self.root or ( self.parent.root if isinstance(self.parent, FieldABC) else self.parent ) def _serialize( self, value: typing.Any, attr: str | None, obj: typing.Any, **kwargs ): """Serializes ``value`` to a basic Python datatype. Noop by default. Concrete :class:`Field` classes should implement this method. Example: :: class TitleCase(Field): def _serialize(self, value, attr, obj, **kwargs): if not value: return "" return str(value).title() :param value: The value to be serialized. :param str attr: The attribute or key on the object to be serialized. :param object obj: The object the value was pulled from. :param dict kwargs: Field-specific keyword arguments. :return: The serialized value """ return value def _deserialize( self, value: typing.Any, attr: str | None, data: typing.Mapping[str, typing.Any] | None, **kwargs, ): """Deserialize value. Concrete :class:`Field` classes should implement this method. :param value: The value to be deserialized. :param attr: The attribute/key in `data` to be deserialized. :param data: The raw input data passed to the `Schema.load`. :param kwargs: Field-specific keyword arguments. :raise ValidationError: In case of formatting or validation failure. :return: The deserialized value. .. versionchanged:: 2.0.0 Added ``attr`` and ``data`` parameters. .. versionchanged:: 3.0.0 Added ``**kwargs`` to signature. """ return value # Properties @property def context(self): """The context dictionary for the parent :class:`Schema`.""" return self.parent.context # the default and missing properties are provided for compatibility and # emit warnings when they are accessed and set @property def default(self): warnings.warn( "The 'default' attribute of fields is deprecated. " "Use 'dump_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) return self.dump_default @default.setter def default(self, value): warnings.warn( "The 'default' attribute of fields is deprecated. " "Use 'dump_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) self.dump_default = value @property def missing(self): warnings.warn( "The 'missing' attribute of fields is deprecated. " "Use 'load_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) return self.load_default @missing.setter def missing(self, value): warnings.warn( "The 'missing' attribute of fields is deprecated. " "Use 'load_default' instead.", RemovedInMarshmallow4Warning, stacklevel=2, ) self.load_default = value
(*, load_default: 'typing.Any' = <marshmallow.missing>, missing: 'typing.Any' = <marshmallow.missing>, dump_default: 'typing.Any' = <marshmallow.missing>, default: 'typing.Any' = <marshmallow.missing>, data_key: 'str | None' = None, attribute: 'str | None' = None, validate: 'None | typing.Callable[[typing.Any], typing.Any] | typing.Iterable[typing.Callable[[typing.Any], typing.Any]]' = None, required: 'bool' = False, allow_none: 'bool | None' = None, load_only: 'bool' = False, dump_only: 'bool' = False, error_messages: 'dict[str, str] | None' = None, metadata: 'typing.Mapping[str, typing.Any] | None' = None, **additional_metadata) -> 'None'
729,882
marshmallow.fields
_deserialize
Deserialize value. Concrete :class:`Field` classes should implement this method. :param value: The value to be deserialized. :param attr: The attribute/key in `data` to be deserialized. :param data: The raw input data passed to the `Schema.load`. :param kwargs: Field-specific keyword arguments. :raise ValidationError: In case of formatting or validation failure. :return: The deserialized value. .. versionchanged:: 2.0.0 Added ``attr`` and ``data`` parameters. .. versionchanged:: 3.0.0 Added ``**kwargs`` to signature.
def _deserialize( self, value: typing.Any, attr: str | None, data: typing.Mapping[str, typing.Any] | None, **kwargs, ): """Deserialize value. Concrete :class:`Field` classes should implement this method. :param value: The value to be deserialized. :param attr: The attribute/key in `data` to be deserialized. :param data: The raw input data passed to the `Schema.load`. :param kwargs: Field-specific keyword arguments. :raise ValidationError: In case of formatting or validation failure. :return: The deserialized value. .. versionchanged:: 2.0.0 Added ``attr`` and ``data`` parameters. .. versionchanged:: 3.0.0 Added ``**kwargs`` to signature. """ return value
(self, value: Any, attr: str | None, data: Optional[Mapping[str, Any]], **kwargs)
729,883
marshmallow.fields
_serialize
Serializes ``value`` to a basic Python datatype. Noop by default. Concrete :class:`Field` classes should implement this method. Example: :: class TitleCase(Field): def _serialize(self, value, attr, obj, **kwargs): if not value: return "" return str(value).title() :param value: The value to be serialized. :param str attr: The attribute or key on the object to be serialized. :param object obj: The object the value was pulled from. :param dict kwargs: Field-specific keyword arguments. :return: The serialized value
def _serialize( self, value: typing.Any, attr: str | None, obj: typing.Any, **kwargs ): """Serializes ``value`` to a basic Python datatype. Noop by default. Concrete :class:`Field` classes should implement this method. Example: :: class TitleCase(Field): def _serialize(self, value, attr, obj, **kwargs): if not value: return "" return str(value).title() :param value: The value to be serialized. :param str attr: The attribute or key on the object to be serialized. :param object obj: The object the value was pulled from. :param dict kwargs: Field-specific keyword arguments. :return: The serialized value """ return value
(self, value: Any, attr: str | None, obj: Any, **kwargs)
729,891
marshmallow_enum
LoadDumpOptions
An enumeration.
class LoadDumpOptions(Enum): value = 1 name = 0
(value, names=None, *, module=None, qualname=None, type=None, start=1)
729,898
verlib2.version
Version
This class abstracts handling of a project's versions. A :class:`Version` instance is comparison aware and can be compared and sorted using the standard Python interfaces. >>> v1 = Version("1.0a5") >>> v2 = Version("1.0") >>> v1 <Version('1.0a5')> >>> v2 <Version('1.0')> >>> v1 < v2 True >>> v1 == v2 False >>> v1 > v2 False >>> v1 >= v2 False >>> v1 <= v2 True
class Version(_BaseVersion): """This class abstracts handling of a project's versions. A :class:`Version` instance is comparison aware and can be compared and sorted using the standard Python interfaces. >>> v1 = Version("1.0a5") >>> v2 = Version("1.0") >>> v1 <Version('1.0a5')> >>> v2 <Version('1.0')> >>> v1 < v2 True >>> v1 == v2 False >>> v1 > v2 False >>> v1 >= v2 False >>> v1 <= v2 True """ _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE) _key: CmpKey def __init__(self, version: str) -> None: """Initialize a Version object. :param version: The string representation of a version which will be parsed and normalized before use. :raises InvalidVersion: If the ``version`` does not conform to PEP 440 in any way then this exception will be raised. """ # Validate the version and parse it into pieces match = self._regex.search(version) if not match: raise InvalidVersion(f"Invalid version: '{version}'") # Store the parsed out pieces of the version self._version = _Version( epoch=int(match.group("epoch")) if match.group("epoch") else 0, release=tuple(int(i) for i in match.group("release").split(".")), pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")), post=_parse_letter_version( match.group("post_l"), match.group("post_n1") or match.group("post_n2") ), dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")), local=_parse_local_version(match.group("local")), ) # Generate a key which will be used for sorting self._key = _cmpkey( self._version.epoch, self._version.release, self._version.pre, self._version.post, self._version.dev, self._version.local, ) def __repr__(self) -> str: """A representation of the Version that shows all internal state. >>> Version('1.0.0') <Version('1.0.0')> """ return f"<Version('{self}')>" def __str__(self) -> str: """A string representation of the version that can be rounded-tripped. >>> str(Version("1.0a5")) '1.0a5' """ parts = [] # Epoch if self.epoch != 0: parts.append(f"{self.epoch}!") # Release segment parts.append(".".join(str(x) for x in self.release)) # Pre-release if self.pre is not None: parts.append("".join(str(x) for x in self.pre)) # Post-release if self.post is not None: parts.append(f".post{self.post}") # Development release if self.dev is not None: parts.append(f".dev{self.dev}") # Local version segment if self.local is not None: parts.append(f"+{self.local}") return "".join(parts) @property def epoch(self) -> int: """The epoch of the version. >>> Version("2.0.0").epoch 0 >>> Version("1!2.0.0").epoch 1 """ return self._version.epoch @property def release(self) -> Tuple[int, ...]: """The components of the "release" segment of the version. >>> Version("1.2.3").release (1, 2, 3) >>> Version("2.0.0").release (2, 0, 0) >>> Version("1!2.0.0.post0").release (2, 0, 0) Includes trailing zeroes but not the epoch or any pre-release / development / post-release suffixes. """ return self._version.release @property def version(self) -> Tuple[int, ...]: """ Return version tuple for backward-compatibility with `distutils.version`. """ return self.release @property def pre(self) -> Optional[Tuple[str, int]]: """The pre-release segment of the version. >>> print(Version("1.2.3").pre) None >>> Version("1.2.3a1").pre ('a', 1) >>> Version("1.2.3b1").pre ('b', 1) >>> Version("1.2.3rc1").pre ('rc', 1) """ return self._version.pre @property def post(self) -> Optional[int]: """The post-release number of the version. >>> print(Version("1.2.3").post) None >>> Version("1.2.3.post1").post 1 """ return self._version.post[1] if self._version.post else None @property def dev(self) -> Optional[int]: """The development number of the version. >>> print(Version("1.2.3").dev) None >>> Version("1.2.3.dev1").dev 1 """ return self._version.dev[1] if self._version.dev else None @property def local(self) -> Optional[str]: """The local version segment of the version. >>> print(Version("1.2.3").local) None >>> Version("1.2.3+abc").local 'abc' """ if self._version.local: return ".".join(str(x) for x in self._version.local) else: return None @property def public(self) -> str: """The public portion of the version. >>> Version("1.2.3").public '1.2.3' >>> Version("1.2.3+abc").public '1.2.3' >>> Version("1.2.3+abc.dev1").public '1.2.3' """ return str(self).split("+", 1)[0] @property def base_version(self) -> str: """The "base version" of the version. >>> Version("1.2.3").base_version '1.2.3' >>> Version("1.2.3+abc").base_version '1.2.3' >>> Version("1!1.2.3+abc.dev1").base_version '1!1.2.3' The "base version" is the public version of the project without any pre or post release markers. """ parts = [] # Epoch if self.epoch != 0: parts.append(f"{self.epoch}!") # Release segment parts.append(".".join(str(x) for x in self.release)) return "".join(parts) @property def is_prerelease(self) -> bool: """Whether this version is a pre-release. >>> Version("1.2.3").is_prerelease False >>> Version("1.2.3a1").is_prerelease True >>> Version("1.2.3b1").is_prerelease True >>> Version("1.2.3rc1").is_prerelease True >>> Version("1.2.3dev1").is_prerelease True """ return self.dev is not None or self.pre is not None @property def is_postrelease(self) -> bool: """Whether this version is a post-release. >>> Version("1.2.3").is_postrelease False >>> Version("1.2.3.post1").is_postrelease True """ return self.post is not None @property def is_devrelease(self) -> bool: """Whether this version is a development release. >>> Version("1.2.3").is_devrelease False >>> Version("1.2.3.dev1").is_devrelease True """ return self.dev is not None @property def major(self) -> int: """The first item of :attr:`release` or ``0`` if unavailable. >>> Version("1.2.3").major 1 """ return self.release[0] if len(self.release) >= 1 else 0 @property def minor(self) -> int: """The second item of :attr:`release` or ``0`` if unavailable. >>> Version("1.2.3").minor 2 >>> Version("1").minor 0 """ return self.release[1] if len(self.release) >= 2 else 0 @property def micro(self) -> int: """The third item of :attr:`release` or ``0`` if unavailable. >>> Version("1.2.3").micro 3 >>> Version("1").micro 0 """ return self.release[2] if len(self.release) >= 3 else 0
(version: str) -> None
729,911
prefect_github.credentials
GitHubCredentials
Block used to manage GitHub authentication. Attributes: token: the token to authenticate into GitHub. Examples: Load stored GitHub credentials: ```python from prefect_github import GitHubCredentials github_credentials_block = GitHubCredentials.load("BLOCK_NAME") ```
class GitHubCredentials(CredentialsBlock): """ Block used to manage GitHub authentication. Attributes: token: the token to authenticate into GitHub. Examples: Load stored GitHub credentials: ```python from prefect_github import GitHubCredentials github_credentials_block = GitHubCredentials.load("BLOCK_NAME") ``` """ _block_type_name = "GitHub Credentials" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/41971cfecfea5f79ff334164f06ecb34d1038dd4-250x250.png" # noqa _documentation_url = "https://prefecthq.github.io/prefect-github/credentials/#prefect_github.credentials.GitHubCredentials" # noqa token: SecretStr = Field( default=None, description="A GitHub personal access token (PAT)." ) def get_client(self) -> HTTPEndpoint: """ Gets an authenticated GitHub GraphQL HTTPEndpoint client. Returns: An authenticated GitHub GraphQL HTTPEndpoint client. Example: Gets an authenticated GitHub GraphQL HTTPEndpoint client. ```python from prefect_github import GitHubCredentials github_credentials = GitHubCredentials(token=token) client = github_credentials.get_client() ``` """ if self.token is not None: base_headers = {"Authorization": f"Bearer {self.token.get_secret_value()}"} else: base_headers = None endpoint = HTTPEndpoint( "https://api.github.com/graphql", base_headers=base_headers ) return endpoint def get_endpoint(self) -> HTTPEndpoint: """ Gets an authenticated GitHub GraphQL HTTPEndpoint. Returns: An authenticated GitHub GraphQL HTTPEndpoint Example: Gets an authenticated GitHub GraphQL HTTPEndpoint. ```python from prefect import flow from prefect_github import GitHubCredentials @flow def example_get_endpoint_flow(): token = "token_xxxxxxx" github_credentials = GitHubCredentials(token=token) endpoint = github_credentials.get_endpoint() return endpoint example_get_endpoint_flow() ``` """ warnings.warn( "`get_endpoint` is deprecated and will be removed March 31st, 2023, " "use `get_client` instead.", DeprecationWarning, ) return self.get_client()
(*args, token: pydantic.v1.types.SecretStr = None, **kwargs) -> None
729,939
prefect_github.credentials
get_client
Gets an authenticated GitHub GraphQL HTTPEndpoint client. Returns: An authenticated GitHub GraphQL HTTPEndpoint client. Example: Gets an authenticated GitHub GraphQL HTTPEndpoint client. ```python from prefect_github import GitHubCredentials github_credentials = GitHubCredentials(token=token) client = github_credentials.get_client() ```
def get_client(self) -> HTTPEndpoint: """ Gets an authenticated GitHub GraphQL HTTPEndpoint client. Returns: An authenticated GitHub GraphQL HTTPEndpoint client. Example: Gets an authenticated GitHub GraphQL HTTPEndpoint client. ```python from prefect_github import GitHubCredentials github_credentials = GitHubCredentials(token=token) client = github_credentials.get_client() ``` """ if self.token is not None: base_headers = {"Authorization": f"Bearer {self.token.get_secret_value()}"} else: base_headers = None endpoint = HTTPEndpoint( "https://api.github.com/graphql", base_headers=base_headers ) return endpoint
(self) -> sgqlc.endpoint.http.HTTPEndpoint
729,940
prefect_github.credentials
get_endpoint
Gets an authenticated GitHub GraphQL HTTPEndpoint. Returns: An authenticated GitHub GraphQL HTTPEndpoint Example: Gets an authenticated GitHub GraphQL HTTPEndpoint. ```python from prefect import flow from prefect_github import GitHubCredentials @flow def example_get_endpoint_flow(): token = "token_xxxxxxx" github_credentials = GitHubCredentials(token=token) endpoint = github_credentials.get_endpoint() return endpoint example_get_endpoint_flow() ```
def get_endpoint(self) -> HTTPEndpoint: """ Gets an authenticated GitHub GraphQL HTTPEndpoint. Returns: An authenticated GitHub GraphQL HTTPEndpoint Example: Gets an authenticated GitHub GraphQL HTTPEndpoint. ```python from prefect import flow from prefect_github import GitHubCredentials @flow def example_get_endpoint_flow(): token = "token_xxxxxxx" github_credentials = GitHubCredentials(token=token) endpoint = github_credentials.get_endpoint() return endpoint example_get_endpoint_flow() ``` """ warnings.warn( "`get_endpoint` is deprecated and will be removed March 31st, 2023, " "use `get_client` instead.", DeprecationWarning, ) return self.get_client()
(self) -> sgqlc.endpoint.http.HTTPEndpoint
729,944
prefect_github.repository
GitHubRepository
Interact with files stored on GitHub repositories.
class GitHubRepository(ReadableDeploymentStorage): """ Interact with files stored on GitHub repositories. """ _block_type_name = "GitHub Repository" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/41971cfecfea5f79ff334164f06ecb34d1038dd4-250x250.png" # noqa: E501 _documentation_url = "https://prefecthq.github.io/prefect-github/repository/#prefect_github.repository.GitHubRepository" # noqa repository_url: str = Field( default=..., title="Repository URL", description=( "The URL of a GitHub repository to read from, in either HTTPS or SSH " "format. If you are using a private repo, it must be in the HTTPS format." ), ) reference: Optional[str] = Field( default=None, description="An optional reference to pin to; can be a branch name or tag.", ) credentials: Optional[GitHubCredentials] = Field( default=None, description="An optional GitHubCredentials block for using private GitHub repos.", # noqa: E501 ) @validator("credentials") def _ensure_credentials_go_with_https(cls, v: str, values: dict): """Ensure that credentials are not provided with 'SSH' formatted GitHub URLs.""" if v is not None: if urlparse(values["repository_url"]).scheme != "https": raise InvalidRepositoryURLError( ( "Crendentials can only be used with GitHub repositories " "using the 'HTTPS' format. You must either remove the " "credential if you wish to use the 'SSH' format and are not " "using a private repository, or you must change the repository " "url to the 'HTTPS' format. " ) ) return v def _create_repo_url(self) -> str: """Format the URL provided to the `git clone` command. For private repos: https://<oauth-key>@github.com/<username>/<repo>.git All other repos should be the same as `self.repository`. """ url_components = urlparse(self.repository_url) if url_components.scheme == "https" and self.credentials is not None: token_value = self.credentials.token.get_secret_value() updated_components = url_components._replace( netloc=f"{token_value}@{url_components.netloc}" ) full_url = urlunparse(updated_components) else: full_url = self.repository_url return full_url @staticmethod def _get_paths( dst_dir: Union[str, None], src_dir: str, sub_directory: str ) -> Tuple[str, str]: """Returns the fully formed paths for GitHubRepository contents in the form (content_source, content_destination). """ if dst_dir is None: content_destination = Path(".").absolute() else: content_destination = Path(dst_dir) content_source = Path(src_dir) if sub_directory: content_destination = content_destination.joinpath(sub_directory) content_source = content_source.joinpath(sub_directory) return str(content_source), str(content_destination) @sync_compatible async def get_directory( self, from_path: Optional[str] = None, local_path: Optional[str] = None ) -> None: """ Clones a GitHub project specified in `from_path` to the provided `local_path`; defaults to cloning the repository reference configured on the Block to the present working directory. Args: from_path: If provided, interpreted as a subdirectory of the underlying repository that will be copied to the provided local path. local_path: A local path to clone to; defaults to present working directory. """ # CONSTRUCT COMMAND cmd = f"git clone {self._create_repo_url()}" if self.reference: cmd += f" -b {self.reference}" # Limit git history cmd += " --depth 1" # Clone to a temporary directory and move the subdirectory over with TemporaryDirectory(suffix="prefect") as tmp_dir: tmp_path_str = tmp_dir cmd += f" {tmp_path_str}" cmd = shlex.split(cmd) err_stream = io.StringIO() out_stream = io.StringIO() process = await run_process(cmd, stream_output=(out_stream, err_stream)) if process.returncode != 0: err_stream.seek(0) raise RuntimeError(f"Failed to pull from remote:\n {err_stream.read()}") content_source, content_destination = self._get_paths( dst_dir=local_path, src_dir=tmp_path_str, sub_directory=from_path ) copy_tree(src=content_source, dst=content_destination)
(*args, repository_url: str, reference: Optional[str] = None, credentials: Optional[prefect_github.credentials.GitHubCredentials] = None, **kwargs) -> None
729,961
prefect_github.repository
_create_repo_url
Format the URL provided to the `git clone` command. For private repos: https://<oauth-key>@github.com/<username>/<repo>.git All other repos should be the same as `self.repository`.
def _create_repo_url(self) -> str: """Format the URL provided to the `git clone` command. For private repos: https://<oauth-key>@github.com/<username>/<repo>.git All other repos should be the same as `self.repository`. """ url_components = urlparse(self.repository_url) if url_components.scheme == "https" and self.credentials is not None: token_value = self.credentials.token.get_secret_value() updated_components = url_components._replace( netloc=f"{token_value}@{url_components.netloc}" ) full_url = urlunparse(updated_components) else: full_url = self.repository_url return full_url
(self) -> str
729,965
prefect_github.repository
_get_paths
Returns the fully formed paths for GitHubRepository contents in the form (content_source, content_destination).
@staticmethod def _get_paths( dst_dir: Union[str, None], src_dir: str, sub_directory: str ) -> Tuple[str, str]: """Returns the fully formed paths for GitHubRepository contents in the form (content_source, content_destination). """ if dst_dir is None: content_destination = Path(".").absolute() else: content_destination = Path(dst_dir) content_source = Path(src_dir) if sub_directory: content_destination = content_destination.joinpath(sub_directory) content_source = content_source.joinpath(sub_directory) return str(content_source), str(content_destination)
(dst_dir: Optional[str], src_dir: str, sub_directory: str) -> Tuple[str, str]
729,974
prefect_github.repository
get_directory
Clones a GitHub project specified in `from_path` to the provided `local_path`; defaults to cloning the repository reference configured on the Block to the present working directory. Args: from_path: If provided, interpreted as a subdirectory of the underlying repository that will be copied to the provided local path. local_path: A local path to clone to; defaults to present working directory.
@task async def query_repository_refs( # noqa owner: str, name: str, ref_prefix: str, github_credentials: GitHubCredentials, follow_renames: bool = True, query: str = None, after: str = None, before: str = None, first: int = None, last: int = None, direction: graphql_schema.OrderDirection = None, order_by: graphql_schema.RefOrder = None, return_fields: Iterable[str] = None, ) -> Dict[str, Any]: # pragma: no cover """ Fetch a list of refs from the repository. Args: owner: The login field of a user or organization. name: The name of the repository. ref_prefix: A ref name prefix like `refs/heads/`, `refs/tags/`, etc. github_credentials: Credentials to use for authentication with GitHub. follow_renames: Follow repository renames. If disabled, a repository referenced by its old name will return an error. query: Filters refs with query on name. after: Returns the elements in the list that come after the specified cursor. before: Returns the elements in the list that come before the specified cursor. first: Returns the first _n_ elements from the list. last: Returns the last _n_ elements from the list. direction: DEPRECATED: use orderBy. The ordering direction. order_by: Ordering options for refs returned from the connection. return_fields: Subset the return fields (as snake_case); defaults to fields listed in configs/query/*.json. Returns: A dict of the returned fields. """ op = Operation(graphql_schema.Query) op_selection = op.repository( **strip_kwargs( owner=owner, name=name, follow_renames=follow_renames, ) ).refs( **strip_kwargs( ref_prefix=ref_prefix, query=query, after=after, before=before, first=first, last=last, direction=direction, order_by=order_by, ) ) op_stack = ( "repository", "refs", ) op_selection = _subset_return_fields( op_selection, op_stack, return_fields, return_fields_defaults ) result = await _execute_graphql_op(op, github_credentials) return result["repository"]["refs"]
(self, from_path: Optional[str] = None, local_path: Optional[str] = None) -> NoneType
729,985
mmengine.fileio.handlers.base
BaseFileHandler
null
class BaseFileHandler(metaclass=ABCMeta): # `str_like` is a flag to indicate whether the type of file object is # str-like object or bytes-like object. Pickle only processes bytes-like # objects but json only processes str-like object. If it is str-like # object, `StringIO` will be used to process the buffer. str_like = True @abstractmethod def load_from_fileobj(self, file, **kwargs): pass @abstractmethod def dump_to_fileobj(self, obj, file, **kwargs): pass @abstractmethod def dump_to_str(self, obj, **kwargs): pass def load_from_path(self, filepath, mode='r', **kwargs): with open(filepath, mode) as f: return self.load_from_fileobj(f, **kwargs) def dump_to_path(self, obj, filepath, mode='w', **kwargs): with open(filepath, mode) as f: self.dump_to_fileobj(obj, f, **kwargs)
()
729,986
mmengine.fileio.handlers.base
dump_to_fileobj
null
@abstractmethod def dump_to_fileobj(self, obj, file, **kwargs): pass
(self, obj, file, **kwargs)
729,987
mmengine.fileio.handlers.base
dump_to_path
null
def dump_to_path(self, obj, filepath, mode='w', **kwargs): with open(filepath, mode) as f: self.dump_to_fileobj(obj, f, **kwargs)
(self, obj, filepath, mode='w', **kwargs)
729,988
mmengine.fileio.handlers.base
dump_to_str
null
@abstractmethod def dump_to_str(self, obj, **kwargs): pass
(self, obj, **kwargs)
729,989
mmengine.fileio.handlers.base
load_from_fileobj
null
@abstractmethod def load_from_fileobj(self, file, **kwargs): pass
(self, file, **kwargs)
729,990
mmengine.fileio.handlers.base
load_from_path
null
def load_from_path(self, filepath, mode='r', **kwargs): with open(filepath, mode) as f: return self.load_from_fileobj(f, **kwargs)
(self, filepath, mode='r', **kwargs)
729,991
mmengine.fileio.backends.base
BaseStorageBackend
Abstract class of storage backends. All backends need to implement two apis: :meth:`get()` and :meth:`get_text()`. - :meth:`get()` reads the file as a byte stream. - :meth:`get_text()` reads the file as texts.
class BaseStorageBackend(metaclass=ABCMeta): """Abstract class of storage backends. All backends need to implement two apis: :meth:`get()` and :meth:`get_text()`. - :meth:`get()` reads the file as a byte stream. - :meth:`get_text()` reads the file as texts. """ # a flag to indicate whether the backend can create a symlink for a file # This attribute will be deprecated in future. _allow_symlink = False @property def allow_symlink(self): print_log( 'allow_symlink will be deprecated in future', logger='current', level=logging.WARNING) return self._allow_symlink @property def name(self): return self.__class__.__name__ @abstractmethod def get(self, filepath): pass @abstractmethod def get_text(self, filepath): pass
()
729,992
mmengine.fileio.backends.base
get
null
@abstractmethod def get(self, filepath): pass
(self, filepath)
729,993
mmengine.fileio.backends.base
get_text
null
@abstractmethod def get_text(self, filepath): pass
(self, filepath)
729,994
mmengine.config.config
Config
A facility for config and config files. It supports common file formats as configs: python/json/yaml. ``Config.fromfile`` can parse a dictionary from a config file, then build a ``Config`` instance with the dictionary. The interface is the same as a dict object and also allows access config values as attributes. Args: cfg_dict (dict, optional): A config dictionary. Defaults to None. cfg_text (str, optional): Text of config. Defaults to None. filename (str or Path, optional): Name of config file. Defaults to None. format_python_code (bool): Whether to format Python code by yapf. Defaults to True. Here is a simple example: Examples: >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) >>> cfg.a 1 >>> cfg.b {'b1': [0, 1]} >>> cfg.b.b1 [0, 1] >>> cfg = Config.fromfile('tests/data/config/a.py') >>> cfg.filename "/home/username/projects/mmengine/tests/data/config/a.py" >>> cfg.item4 'test' >>> cfg "Config [path: /home/username/projects/mmengine/tests/data/config/a.py] :" "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" You can find more advance usage in the `config tutorial`_. .. _config tutorial: https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html
class Config: """A facility for config and config files. It supports common file formats as configs: python/json/yaml. ``Config.fromfile`` can parse a dictionary from a config file, then build a ``Config`` instance with the dictionary. The interface is the same as a dict object and also allows access config values as attributes. Args: cfg_dict (dict, optional): A config dictionary. Defaults to None. cfg_text (str, optional): Text of config. Defaults to None. filename (str or Path, optional): Name of config file. Defaults to None. format_python_code (bool): Whether to format Python code by yapf. Defaults to True. Here is a simple example: Examples: >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) >>> cfg.a 1 >>> cfg.b {'b1': [0, 1]} >>> cfg.b.b1 [0, 1] >>> cfg = Config.fromfile('tests/data/config/a.py') >>> cfg.filename "/home/username/projects/mmengine/tests/data/config/a.py" >>> cfg.item4 'test' >>> cfg "Config [path: /home/username/projects/mmengine/tests/data/config/a.py] :" "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}" You can find more advance usage in the `config tutorial`_. .. _config tutorial: https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html """ # noqa: E501 def __init__( self, cfg_dict: dict = None, cfg_text: Optional[str] = None, filename: Optional[Union[str, Path]] = None, env_variables: Optional[dict] = None, format_python_code: bool = True, ): filename = str(filename) if isinstance(filename, Path) else filename if cfg_dict is None: cfg_dict = dict() elif not isinstance(cfg_dict, dict): raise TypeError('cfg_dict must be a dict, but ' f'got {type(cfg_dict)}') for key in cfg_dict: if key in RESERVED_KEYS: raise KeyError(f'{key} is reserved for config file') if not isinstance(cfg_dict, ConfigDict): cfg_dict = ConfigDict(cfg_dict) super().__setattr__('_cfg_dict', cfg_dict) super().__setattr__('_filename', filename) super().__setattr__('_format_python_code', format_python_code) if not hasattr(self, '_imported_names'): super().__setattr__('_imported_names', set()) if cfg_text: text = cfg_text elif filename: with open(filename, encoding='utf-8') as f: text = f.read() else: text = '' super().__setattr__('_text', text) if env_variables is None: env_variables = dict() super().__setattr__('_env_variables', env_variables) @staticmethod def fromfile(filename: Union[str, Path], use_predefined_variables: bool = True, import_custom_modules: bool = True, use_environment_variables: bool = True, lazy_import: Optional[bool] = None, format_python_code: bool = True) -> 'Config': """Build a Config instance from config file. Args: filename (str or Path): Name of config file. use_predefined_variables (bool, optional): Whether to use predefined variables. Defaults to True. import_custom_modules (bool, optional): Whether to support importing custom modules in config. Defaults to None. use_environment_variables (bool, optional): Whether to use environment variables. Defaults to True. lazy_import (bool): Whether to load config in `lazy_import` mode. If it is `None`, it will be deduced by the content of the config file. Defaults to None. format_python_code (bool): Whether to format Python code by yapf. Defaults to True. Returns: Config: Config instance built from config file. """ filename = str(filename) if isinstance(filename, Path) else filename if lazy_import is False or \ lazy_import is None and not Config._is_lazy_import(filename): cfg_dict, cfg_text, env_variables = Config._file2dict( filename, use_predefined_variables, use_environment_variables, lazy_import) if import_custom_modules and cfg_dict.get('custom_imports', None): try: import_modules_from_strings(**cfg_dict['custom_imports']) except ImportError as e: err_msg = ( 'Failed to import custom modules from ' f"{cfg_dict['custom_imports']}, the current sys.path " 'is: ') for p in sys.path: err_msg += f'\n {p}' err_msg += ( '\nYou should set `PYTHONPATH` to make `sys.path` ' 'include the directory which contains your custom ' 'module') raise ImportError(err_msg) from e return Config( cfg_dict, cfg_text=cfg_text, filename=filename, env_variables=env_variables, ) else: # Enable lazy import when parsing the config. # Using try-except to make sure ``ConfigDict.lazy`` will be reset # to False. See more details about lazy in the docstring of # ConfigDict ConfigDict.lazy = True try: cfg_dict, imported_names = Config._parse_lazy_import(filename) except Exception as e: raise e finally: # disable lazy import to get the real type. See more details # about lazy in the docstring of ConfigDict ConfigDict.lazy = False cfg = Config( cfg_dict, filename=filename, format_python_code=format_python_code) object.__setattr__(cfg, '_imported_names', imported_names) return cfg @staticmethod def fromstring(cfg_str: str, file_format: str) -> 'Config': """Build a Config instance from config text. Args: cfg_str (str): Config text. file_format (str): Config file format corresponding to the config str. Only py/yml/yaml/json type are supported now! Returns: Config: Config object generated from ``cfg_str``. """ if file_format not in ['.py', '.json', '.yaml', '.yml']: raise OSError('Only py/yml/yaml/json type are supported now!') if file_format != '.py' and 'dict(' in cfg_str: # check if users specify a wrong suffix for python warnings.warn( 'Please check "file_format", the file format may be .py') # A temporary file can not be opened a second time on Windows. # See https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile for more details. # noqa # `temp_file` is opened first in `tempfile.NamedTemporaryFile` and # second in `Config.from_file`. # In addition, a named temporary file will be removed after closed. # As a workaround we set `delete=False` and close the temporary file # before opening again. with tempfile.NamedTemporaryFile( 'w', encoding='utf-8', suffix=file_format, delete=False) as temp_file: temp_file.write(cfg_str) cfg = Config.fromfile(temp_file.name) os.remove(temp_file.name) # manually delete the temporary file return cfg @staticmethod def _get_base_modules(nodes: list) -> list: """Get base module name from parsed code. Args: nodes (list): Parsed code of the config file. Returns: list: Name of base modules. """ def _get_base_module_from_with(with_nodes: list) -> list: """Get base module name from if statement in python file. Args: with_nodes (list): List of if statement. Returns: list: Name of base modules. """ base_modules = [] for node in with_nodes: assert isinstance(node, ast.ImportFrom), ( 'Illegal syntax in config file! Only ' '`from ... import ...` could be implemented` in ' 'with read_base()`') assert node.module is not None, ( 'Illegal syntax in config file! Syntax like ' '`from . import xxx` is not allowed in `with read_base()`') base_modules.append(node.level * '.' + node.module) return base_modules for idx, node in enumerate(nodes): if (isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) and node.targets[0].id == BASE_KEY): raise ConfigParsingError( 'The configuration file type in the inheritance chain ' 'must match the current configuration file type, either ' '"lazy_import" or non-"lazy_import". You got this error ' f'since you use the syntax like `_base_ = "{node.targets[0].id}"` ' # noqa: E501 'in your config. You should use `with read_base(): ... to` ' # noqa: E501 'mark the inherited config file. See more information ' 'in https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html' # noqa: E501 ) if not isinstance(node, ast.With): continue expr = node.items[0].context_expr if (not isinstance(expr, ast.Call) or not expr.func.id == 'read_base' or # type: ignore len(node.items) > 1): raise ConfigParsingError( 'Only `read_base` context manager can be used in the ' 'config') # The original code: # ``` # with read_base(): # from .._base_.default_runtime import * # ``` # The processed code: # ``` # from .._base_.default_runtime import * # ``` # As you can see, the if statement is removed and the # from ... import statement will be unindent for nested_idx, nested_node in enumerate(node.body): nodes.insert(idx + nested_idx + 1, nested_node) nodes.pop(idx) return _get_base_module_from_with(node.body) return [] @staticmethod def _validate_py_syntax(filename: str): """Validate syntax of python config. Args: filename (str): Filename of python config file. """ with open(filename, encoding='utf-8') as f: content = f.read() try: ast.parse(content) except SyntaxError as e: raise SyntaxError('There are syntax errors in config ' f'file {filename}: {e}') @staticmethod def _substitute_predefined_vars(filename: str, temp_config_name: str): """Substitute predefined variables in config with actual values. Sometimes we want some variables in the config to be related to the current path or file name, etc. Here is an example of a typical usage scenario. When training a model, we define a working directory in the config that save the models and logs. For different configs, we expect to define different working directories. A common way for users is to use the config file name directly as part of the working directory name, e.g. for the config ``config_setting1.py``, the working directory is ``. /work_dir/config_setting1``. This can be easily achieved using predefined variables, which can be written in the config `config_setting1.py` as follows .. code-block:: python work_dir = '. /work_dir/{{ fileBasenameNoExtension }}' Here `{{ fileBasenameNoExtension }}` indicates the file name of the config (without the extension), and when the config class reads the config file, it will automatically parse this double-bracketed string to the corresponding actual value. .. code-block:: python cfg = Config.fromfile('. /config_setting1.py') cfg.work_dir # ". /work_dir/config_setting1" For details, Please refer to docs/zh_cn/advanced_tutorials/config.md . Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. """ file_dirname = osp.dirname(filename) file_basename = osp.basename(filename) file_basename_no_extension = osp.splitext(file_basename)[0] file_extname = osp.splitext(filename)[1] support_templates = dict( fileDirname=file_dirname, fileBasename=file_basename, fileBasenameNoExtension=file_basename_no_extension, fileExtname=file_extname) with open(filename, encoding='utf-8') as f: config_file = f.read() for key, value in support_templates.items(): regexp = r'\{\{\s*' + str(key) + r'\s*\}\}' value = value.replace('\\', '/') config_file = re.sub(regexp, value, config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) @staticmethod def _substitute_env_variables(filename: str, temp_config_name: str): """Substitute environment variables in config with actual values. Sometimes, we want to change some items in the config with environment variables. For examples, we expect to change dataset root by setting ``DATASET_ROOT=/dataset/root/path`` in the command line. This can be easily achieved by writing lines in the config as follows .. code-block:: python data_root = '{{$DATASET_ROOT:/default/dataset}}/images' Here, ``{{$DATASET_ROOT:/default/dataset}}`` indicates using the environment variable ``DATASET_ROOT`` to replace the part between ``{{}}``. If the ``DATASET_ROOT`` is not set, the default value ``/default/dataset`` will be used. Environment variables not only can replace items in the string, they can also substitute other types of data in config. In this situation, we can write the config as below .. code-block:: python model = dict( bbox_head = dict(num_classes={{'$NUM_CLASSES:80'}})) For details, Please refer to docs/zh_cn/tutorials/config.md . Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. """ with open(filename, encoding='utf-8') as f: config_file = f.read() regexp = r'\{\{[\'\"]?\s*\$(\w+)\s*\:\s*(\S*?)\s*[\'\"]?\}\}' keys = re.findall(regexp, config_file) env_variables = dict() for var_name, value in keys: regexp = r'\{\{[\'\"]?\s*\$' + var_name + r'\s*\:\s*' \ + value + r'\s*[\'\"]?\}\}' if var_name in os.environ: value = os.environ[var_name] env_variables[var_name] = value print_log( f'Using env variable `{var_name}` with value of ' f'{value} to replace item in config.', logger='current') if not value: raise KeyError(f'`{var_name}` cannot be found in `os.environ`.' f' Please set `{var_name}` in environment or ' 'give a default value.') config_file = re.sub(regexp, value, config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) return env_variables @staticmethod def _pre_substitute_base_vars(filename: str, temp_config_name: str) -> dict: """Preceding step for substituting variables in base config with actual value. Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. Returns: dict: A dictionary contains variables in base config. """ with open(filename, encoding='utf-8') as f: config_file = f.read() base_var_dict = {} regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}' base_vars = set(re.findall(regexp, config_file)) for base_var in base_vars: randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}' base_var_dict[randstr] = base_var regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}' config_file = re.sub(regexp, f'"{randstr}"', config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) return base_var_dict @staticmethod def _substitute_base_vars(cfg: Any, base_var_dict: dict, base_cfg: dict) -> Any: """Substitute base variables from strings to their actual values. Args: Any : Config dictionary. base_var_dict (dict): A dictionary contains variables in base config. base_cfg (dict): Base config dictionary. Returns: Any : A dictionary with origin base variables substituted with actual values. """ cfg = copy.deepcopy(cfg) if isinstance(cfg, dict): for k, v in cfg.items(): if isinstance(v, str) and v in base_var_dict: new_v = base_cfg for new_k in base_var_dict[v].split('.'): new_v = new_v[new_k] cfg[k] = new_v elif isinstance(v, (list, tuple, dict)): cfg[k] = Config._substitute_base_vars( v, base_var_dict, base_cfg) elif isinstance(cfg, tuple): cfg = tuple( Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg) elif isinstance(cfg, list): cfg = [ Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg ] elif isinstance(cfg, str) and cfg in base_var_dict: new_v = base_cfg for new_k in base_var_dict[cfg].split('.'): new_v = new_v[new_k] cfg = new_v return cfg @staticmethod def _file2dict( filename: str, use_predefined_variables: bool = True, use_environment_variables: bool = True, lazy_import: Optional[bool] = None) -> Tuple[dict, str, dict]: """Transform file to variables dictionary. Args: filename (str): Name of config file. use_predefined_variables (bool, optional): Whether to use predefined variables. Defaults to True. use_environment_variables (bool, optional): Whether to use environment variables. Defaults to True. lazy_import (bool): Whether to load config in `lazy_import` mode. If it is `None`, it will be deduced by the content of the config file. Defaults to None. Returns: Tuple[dict, str]: Variables dictionary and text of Config. """ if lazy_import is None and Config._is_lazy_import(filename): raise RuntimeError( 'The configuration file type in the inheritance chain ' 'must match the current configuration file type, either ' '"lazy_import" or non-"lazy_import". You got this error ' 'since you use the syntax like `with read_base(): ...` ' f'or import non-builtin module in {filename}. See more ' 'information in https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html' # noqa: E501 ) filename = osp.abspath(osp.expanduser(filename)) check_file_exist(filename) fileExtname = osp.splitext(filename)[1] if fileExtname not in ['.py', '.json', '.yaml', '.yml']: raise OSError('Only py/yml/yaml/json type are supported now!') try: with tempfile.TemporaryDirectory() as temp_config_dir: temp_config_file = tempfile.NamedTemporaryFile( dir=temp_config_dir, suffix=fileExtname, delete=False) if platform.system() == 'Windows': temp_config_file.close() # Substitute predefined variables if use_predefined_variables: Config._substitute_predefined_vars(filename, temp_config_file.name) else: shutil.copyfile(filename, temp_config_file.name) # Substitute environment variables env_variables = dict() if use_environment_variables: env_variables = Config._substitute_env_variables( temp_config_file.name, temp_config_file.name) # Substitute base variables from placeholders to strings base_var_dict = Config._pre_substitute_base_vars( temp_config_file.name, temp_config_file.name) # Handle base files base_cfg_dict = ConfigDict() cfg_text_list = list() for base_cfg_path in Config._get_base_files( temp_config_file.name): base_cfg_path, scope = Config._get_cfg_path( base_cfg_path, filename) _cfg_dict, _cfg_text, _env_variables = Config._file2dict( filename=base_cfg_path, use_predefined_variables=use_predefined_variables, use_environment_variables=use_environment_variables, lazy_import=lazy_import, ) cfg_text_list.append(_cfg_text) env_variables.update(_env_variables) duplicate_keys = base_cfg_dict.keys() & _cfg_dict.keys() if len(duplicate_keys) > 0: raise KeyError( 'Duplicate key is not allowed among bases. ' f'Duplicate keys: {duplicate_keys}') # _dict_to_config_dict will do the following things: # 1. Recursively converts ``dict`` to :obj:`ConfigDict`. # 2. Set `_scope_` for the outer dict variable for the base # config. # 3. Set `scope` attribute for each base variable. # Different from `_scope_`, `scope` is not a key of base # dict, `scope` attribute will be parsed to key `_scope_` # by function `_parse_scope` only if the base variable is # accessed by the current config. _cfg_dict = Config._dict_to_config_dict(_cfg_dict, scope) base_cfg_dict.update(_cfg_dict) if filename.endswith('.py'): with open(temp_config_file.name, encoding='utf-8') as f: parsed_codes = ast.parse(f.read()) parsed_codes = RemoveAssignFromAST(BASE_KEY).visit( parsed_codes) codeobj = compile(parsed_codes, filename, mode='exec') # Support load global variable in nested function of the # config. global_locals_var = {BASE_KEY: base_cfg_dict} ori_keys = set(global_locals_var.keys()) eval(codeobj, global_locals_var, global_locals_var) cfg_dict = { key: value for key, value in global_locals_var.items() if (key not in ori_keys and not key.startswith('__')) } elif filename.endswith(('.yml', '.yaml', '.json')): cfg_dict = load(temp_config_file.name) # close temp file for key, value in list(cfg_dict.items()): if isinstance(value, (types.FunctionType, types.ModuleType)): cfg_dict.pop(key) temp_config_file.close() # If the current config accesses a base variable of base # configs, The ``scope`` attribute of corresponding variable # will be converted to the `_scope_`. Config._parse_scope(cfg_dict) except Exception as e: if osp.exists(temp_config_dir): shutil.rmtree(temp_config_dir) raise e # check deprecation information if DEPRECATION_KEY in cfg_dict: deprecation_info = cfg_dict.pop(DEPRECATION_KEY) warning_msg = f'The config file {filename} will be deprecated ' \ 'in the future.' if 'expected' in deprecation_info: warning_msg += f' Please use {deprecation_info["expected"]} ' \ 'instead.' if 'reference' in deprecation_info: warning_msg += ' More information can be found at ' \ f'{deprecation_info["reference"]}' warnings.warn(warning_msg, DeprecationWarning) cfg_text = filename + '\n' with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows cfg_text += f.read() # Substitute base variables from strings to their actual values cfg_dict = Config._substitute_base_vars(cfg_dict, base_var_dict, base_cfg_dict) cfg_dict.pop(BASE_KEY, None) cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict) cfg_dict = { k: v for k, v in cfg_dict.items() if not k.startswith('__') } # merge cfg_text cfg_text_list.append(cfg_text) cfg_text = '\n'.join(cfg_text_list) return cfg_dict, cfg_text, env_variables @staticmethod def _parse_lazy_import(filename: str) -> Tuple[ConfigDict, set]: """Transform file to variables dictionary. Args: filename (str): Name of config file. Returns: Tuple[dict, dict]: ``cfg_dict`` and ``imported_names``. - cfg_dict (dict): Variables dictionary of parsed config. - imported_names (set): Used to mark the names of imported object. """ # In lazy import mode, users can use the Python syntax `import` to # implement inheritance between configuration files, which is easier # for users to understand the hierarchical relationships between # different configuration files. # Besides, users can also using `import` syntax to import corresponding # module which will be filled in the `type` field. It means users # can directly navigate to the source of the module in the # configuration file by clicking the `type` field. # To avoid really importing the third party package like `torch` # during import `type` object, we use `_parse_lazy_import` to parse the # configuration file, which will not actually trigger the import # process, but simply parse the imported `type`s as LazyObject objects. # The overall pipeline of _parse_lazy_import is: # 1. Parse the base module from the config file. # || # \/ # base_module = ['mmdet.configs.default_runtime'] # || # \/ # 2. recursively parse the base module and gather imported objects to # a dict. # || # \/ # The base_dict will be: # { # 'mmdet.configs.default_runtime': {...} # 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...} # ... # }, each item in base_dict is a dict of `LazyObject` # 3. parse the current config file filling the imported variable # with the base_dict. # # 4. During the parsing process, all imported variable will be # recorded in the `imported_names` set. These variables can be # accessed, but will not be dumped by default. with open(filename, encoding='utf-8') as f: global_dict = {'LazyObject': LazyObject, '__file__': filename} base_dict = {} parsed_codes = ast.parse(f.read()) # get the names of base modules, and remove the # `with read_base():'` statement base_modules = Config._get_base_modules(parsed_codes.body) base_imported_names = set() for base_module in base_modules: # If base_module means a relative import, assuming the level is # 2, which means the module is imported like # "from ..a.b import c". we must ensure that c is an # object `defined` in module b, and module b should not be a # package including `__init__` file but a single python file. level = len(re.match(r'\.*', base_module).group()) if level > 0: # Relative import base_dir = osp.dirname(filename) module_path = osp.join( base_dir, *(['..'] * (level - 1)), f'{base_module[level:].replace(".", "/")}.py') else: # Absolute import module_list = base_module.split('.') if len(module_list) == 1: raise ConfigParsingError( 'The imported configuration file should not be ' f'an independent package {module_list[0]}. Here ' 'is an example: ' '`with read_base(): from mmdet.configs.retinanet_r50_fpn_1x_coco import *`' # noqa: E501 ) else: package = module_list[0] root_path = get_installed_path(package) module_path = f'{osp.join(root_path, *module_list[1:])}.py' # noqa: E501 if not osp.isfile(module_path): raise ConfigParsingError( f'{module_path} not found! It means that incorrect ' 'module is defined in ' f'`with read_base(): = from {base_module} import ...`, please ' # noqa: E501 'make sure the base config module is valid ' 'and is consistent with the prior import ' 'logic') _base_cfg_dict, _base_imported_names = Config._parse_lazy_import( # noqa: E501 module_path) base_imported_names |= _base_imported_names # The base_dict will be: # { # 'mmdet.configs.default_runtime': {...} # 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...} # ... # } base_dict[base_module] = _base_cfg_dict # `base_dict` contains all the imported modules from `base_cfg`. # In order to collect the specific imported module from `base_cfg` # before parse the current file, we using AST Transform to # transverse the imported module from base_cfg and merge then into # the global dict. After the ast transformation, most of import # syntax will be removed (except for the builtin import) and # replaced with the `LazyObject` transform = ImportTransformer( global_dict=global_dict, base_dict=base_dict, filename=filename) modified_code = transform.visit(parsed_codes) modified_code, abs_imported = _gather_abs_import_lazyobj( modified_code, filename=filename) imported_names = transform.imported_obj | abs_imported imported_names |= base_imported_names modified_code = ast.fix_missing_locations(modified_code) exec( compile(modified_code, filename, mode='exec'), global_dict, global_dict) ret: dict = {} for key, value in global_dict.items(): if key.startswith('__') or key in ['LazyObject']: continue ret[key] = value # convert dict to ConfigDict cfg_dict = Config._dict_to_config_dict_lazy(ret) return cfg_dict, imported_names @staticmethod def _dict_to_config_dict_lazy(cfg: dict): """Recursively converts ``dict`` to :obj:`ConfigDict`. The only difference between ``_dict_to_config_dict_lazy`` and ``_dict_to_config_dict_lazy`` is that the former one does not consider the scope, and will not trigger the building of ``LazyObject``. Args: cfg (dict): Config dict. Returns: ConfigDict: Converted dict. """ # Only the outer dict with key `type` should have the key `_scope_`. if isinstance(cfg, dict): cfg_dict = ConfigDict() for key, value in cfg.items(): cfg_dict[key] = Config._dict_to_config_dict_lazy(value) return cfg_dict if isinstance(cfg, (tuple, list)): return type(cfg)( Config._dict_to_config_dict_lazy(_cfg) for _cfg in cfg) return cfg @staticmethod def _dict_to_config_dict(cfg: dict, scope: Optional[str] = None, has_scope=True): """Recursively converts ``dict`` to :obj:`ConfigDict`. Args: cfg (dict): Config dict. scope (str, optional): Scope of instance. has_scope (bool): Whether to add `_scope_` key to config dict. Returns: ConfigDict: Converted dict. """ # Only the outer dict with key `type` should have the key `_scope_`. if isinstance(cfg, dict): if has_scope and 'type' in cfg: has_scope = False if scope is not None and cfg.get('_scope_', None) is None: cfg._scope_ = scope # type: ignore cfg = ConfigDict(cfg) dict.__setattr__(cfg, 'scope', scope) for key, value in cfg.items(): cfg[key] = Config._dict_to_config_dict( value, scope=scope, has_scope=has_scope) elif isinstance(cfg, tuple): cfg = tuple( Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope) for _cfg in cfg) elif isinstance(cfg, list): cfg = [ Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope) for _cfg in cfg ] return cfg @staticmethod def _parse_scope(cfg: dict) -> None: """Adds ``_scope_`` to :obj:`ConfigDict` instance, which means a base variable. If the config dict already has the scope, scope will not be overwritten. Args: cfg (dict): Config needs to be parsed with scope. """ if isinstance(cfg, ConfigDict): cfg._scope_ = cfg.scope elif isinstance(cfg, (tuple, list)): [Config._parse_scope(value) for value in cfg] else: return @staticmethod def _get_base_files(filename: str) -> list: """Get the base config file. Args: filename (str): The config file. Raises: TypeError: Name of config file. Returns: list: A list of base config. """ file_format = osp.splitext(filename)[1] if file_format == '.py': Config._validate_py_syntax(filename) with open(filename, encoding='utf-8') as f: parsed_codes = ast.parse(f.read()).body def is_base_line(c): return (isinstance(c, ast.Assign) and isinstance(c.targets[0], ast.Name) and c.targets[0].id == BASE_KEY) base_code = next((c for c in parsed_codes if is_base_line(c)), None) if base_code is not None: base_code = ast.Expression( # type: ignore body=base_code.value) # type: ignore base_files = eval(compile(base_code, '', mode='eval')) else: base_files = [] elif file_format in ('.yml', '.yaml', '.json'): import mmengine cfg_dict = mmengine.load(filename) base_files = cfg_dict.get(BASE_KEY, []) else: raise ConfigParsingError( 'The config type should be py, json, yaml or ' f'yml, but got {file_format}') base_files = base_files if isinstance(base_files, list) else [base_files] return base_files @staticmethod def _get_cfg_path(cfg_path: str, filename: str) -> Tuple[str, Optional[str]]: """Get the config path from the current or external package. Args: cfg_path (str): Relative path of config. filename (str): The config file being parsed. Returns: Tuple[str, str or None]: Path and scope of config. If the config is not an external config, the scope will be `None`. """ if '::' in cfg_path: # `cfg_path` startswith '::' means an external config path. # Get package name and relative config path. scope = cfg_path.partition('::')[0] package, cfg_path = _get_package_and_cfg_path(cfg_path) if not is_installed(package): raise ModuleNotFoundError( f'{package} is not installed, please install {package} ' f'manually') # Get installed package path. package_path = get_installed_path(package) try: # Get config path from meta file. cfg_path = _get_external_cfg_path(package_path, cfg_path) except ValueError: # Since base config does not have a metafile, it should be # concatenated with package path and relative config path. cfg_path = _get_external_cfg_base_path(package_path, cfg_path) except FileNotFoundError as e: raise e return cfg_path, scope else: # Get local config path. cfg_dir = osp.dirname(filename) cfg_path = osp.join(cfg_dir, cfg_path) return cfg_path, None @staticmethod def _merge_a_into_b(a: dict, b: dict, allow_list_keys: bool = False) -> dict: """merge dict ``a`` into dict ``b`` (non-inplace). Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid in-place modifications. Args: a (dict): The source dict to be merged into ``b``. b (dict): The origin dict to be fetch keys from ``a``. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in source ``a`` and will replace the element of the corresponding index in b if b is a list. Defaults to False. Returns: dict: The modified dict of ``b`` using ``a``. Examples: # Normally merge a into b. >>> Config._merge_a_into_b( ... dict(obj=dict(a=2)), dict(obj=dict(a=1))) {'obj': {'a': 2}} # Delete b first and merge a into b. >>> Config._merge_a_into_b( ... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1))) {'obj': {'a': 2}} # b is a list >>> Config._merge_a_into_b( ... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True) [{'a': 2}, {'b': 2}] """ b = b.copy() for k, v in a.items(): if allow_list_keys and k.isdigit() and isinstance(b, list): k = int(k) if len(b) <= k: raise KeyError(f'Index {k} exceeds the length of list {b}') b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys) elif isinstance(v, dict): if k in b and not v.pop(DELETE_KEY, False): allowed_types: Union[Tuple, type] = ( dict, list) if allow_list_keys else dict if not isinstance(b[k], allowed_types): raise TypeError( f'{k}={v} in child config cannot inherit from ' f'base because {k} is a dict in the child config ' f'but is of type {type(b[k])} in base config. ' f'You may set `{DELETE_KEY}=True` to ignore the ' f'base config.') b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys) else: b[k] = ConfigDict(v) else: b[k] = v return b @staticmethod def auto_argparser(description=None): """Generate argparser from config file automatically (experimental)""" partial_parser = ArgumentParser(description=description) partial_parser.add_argument('config', help='config file path') cfg_file = partial_parser.parse_known_args()[0].config cfg = Config.fromfile(cfg_file) parser = ArgumentParser(description=description) parser.add_argument('config', help='config file path') add_args(parser, cfg) return parser, cfg @property def filename(self) -> str: """get file name of config.""" return self._filename @property def text(self) -> str: """get config text.""" return self._text @property def env_variables(self) -> dict: """get used environment variables.""" return self._env_variables @property def pretty_text(self) -> str: """get formatted python config text.""" indent = 4 def _indent(s_, num_spaces): s = s_.split('\n') if len(s) == 1: return s_ first = s.pop(0) s = [(num_spaces * ' ') + line for line in s] s = '\n'.join(s) s = first + '\n' + s return s def _format_basic_types(k, v, use_mapping=False): if isinstance(v, str): v_str = repr(v) else: v_str = str(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: {v_str}' else: attr_str = f'{str(k)}={v_str}' attr_str = _indent(attr_str, indent) return attr_str def _format_list_tuple(k, v, use_mapping=False): if isinstance(v, list): left = '[' right = ']' else: left = '(' right = ')' v_str = f'{left}\n' # check if all items in the list are dict for item in v: if isinstance(item, dict): v_str += f'dict({_indent(_format_dict(item), indent)}),\n' elif isinstance(item, tuple): v_str += f'{_indent(_format_list_tuple(None, item), indent)},\n' # noqa: 501 elif isinstance(item, list): v_str += f'{_indent(_format_list_tuple(None, item), indent)},\n' # noqa: 501 elif isinstance(item, str): v_str += f'{_indent(repr(item), indent)},\n' else: v_str += str(item) + ',\n' if k is None: return _indent(v_str, indent) + right if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: {v_str}' else: attr_str = f'{str(k)}={v_str}' attr_str = _indent(attr_str, indent) + right return attr_str def _contain_invalid_identifier(dict_str): contain_invalid_identifier = False for key_name in dict_str: contain_invalid_identifier |= \ (not str(key_name).isidentifier()) return contain_invalid_identifier def _format_dict(input_dict, outest_level=False): r = '' s = [] use_mapping = _contain_invalid_identifier(input_dict) if use_mapping: r += '{' for idx, (k, v) in enumerate( sorted(input_dict.items(), key=lambda x: str(x[0]))): is_last = idx >= len(input_dict) - 1 end = '' if outest_level or is_last else ',' if isinstance(v, dict): v_str = '\n' + _format_dict(v) if use_mapping: k_str = f"'{k}'" if isinstance(k, str) else str(k) attr_str = f'{k_str}: dict({v_str}' else: attr_str = f'{str(k)}=dict({v_str}' attr_str = _indent(attr_str, indent) + ')' + end elif isinstance(v, (list, tuple)): attr_str = _format_list_tuple(k, v, use_mapping) + end else: attr_str = _format_basic_types(k, v, use_mapping) + end s.append(attr_str) r += '\n'.join(s) if use_mapping: r += '}' return r cfg_dict = self.to_dict() text = _format_dict(cfg_dict, outest_level=True) if self._format_python_code: # copied from setup.cfg yapf_style = dict( based_on_style='pep8', blank_line_before_nested_class_or_def=True, split_before_expression_after_opening_paren=True) try: if digit_version(yapf.__version__) >= digit_version('0.40.2'): text, _ = FormatCode(text, style_config=yapf_style) else: text, _ = FormatCode( text, style_config=yapf_style, verify=True) except: # noqa: E722 raise SyntaxError('Failed to format the config file, please ' f'check the syntax of: \n{text}') return text def __repr__(self): return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}' def __len__(self): return len(self._cfg_dict) def __getattr__(self, name: str) -> Any: return getattr(self._cfg_dict, name) def __getitem__(self, name): return self._cfg_dict.__getitem__(name) def __setattr__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setattr__(name, value) def __setitem__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setitem__(name, value) def __iter__(self): return iter(self._cfg_dict) def __getstate__( self ) -> Tuple[dict, Optional[str], Optional[str], dict, bool, set]: state = (self._cfg_dict, self._filename, self._text, self._env_variables, self._format_python_code, self._imported_names) return state def __deepcopy__(self, memo): cls = self.__class__ other = cls.__new__(cls) memo[id(self)] = other for key, value in self.__dict__.items(): super(Config, other).__setattr__(key, copy.deepcopy(value, memo)) return other def __copy__(self): cls = self.__class__ other = cls.__new__(cls) other.__dict__.update(self.__dict__) super(Config, other).__setattr__('_cfg_dict', self._cfg_dict.copy()) return other copy = __copy__ def __setstate__(self, state: Tuple[dict, Optional[str], Optional[str], dict, bool, set]): super().__setattr__('_cfg_dict', state[0]) super().__setattr__('_filename', state[1]) super().__setattr__('_text', state[2]) super().__setattr__('_env_variables', state[3]) super().__setattr__('_format_python_code', state[4]) super().__setattr__('_imported_names', state[5]) def dump(self, file: Optional[Union[str, Path]] = None): """Dump config to file or return config text. Args: file (str or Path, optional): If not specified, then the object is dumped to a str, otherwise to a file specified by the filename. Defaults to None. Returns: str or None: Config text. """ file = str(file) if isinstance(file, Path) else file cfg_dict = self.to_dict() if file is None: if self.filename is None or self.filename.endswith('.py'): return self.pretty_text else: file_format = self.filename.split('.')[-1] return dump(cfg_dict, file_format=file_format) elif file.endswith('.py'): with open(file, 'w', encoding='utf-8') as f: f.write(self.pretty_text) else: file_format = file.split('.')[-1] return dump(cfg_dict, file=file, file_format=file_format) def merge_from_dict(self, options: dict, allow_list_keys: bool = True) -> None: """Merge list into cfg_dict. Merge the dict parsed by MultipleKVAction into this cfg. Args: options (dict): dict of configs to merge from. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in ``options`` and will replace the element of the corresponding index in the config if the config is a list. Defaults to True. Examples: >>> from mmengine import Config >>> # Merge dictionary element >>> options = {'model.backbone.depth': 50, 'model.backbone.with_cp': True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg._cfg_dict {'model': {'backbone': {'type': 'ResNet', 'depth': 50, 'with_cp': True}}} >>> # Merge list element >>> cfg = Config( >>> dict(pipeline=[dict(type='LoadImage'), >>> dict(type='LoadAnnotations')])) >>> options = dict(pipeline={'0': dict(type='SelfLoadImage')}) >>> cfg.merge_from_dict(options, allow_list_keys=True) >>> cfg._cfg_dict {'pipeline': [{'type': 'SelfLoadImage'}, {'type': 'LoadAnnotations'}]} """ # noqa: E501 option_cfg_dict: dict = {} for full_key, v in options.items(): d = option_cfg_dict key_list = full_key.split('.') for subkey in key_list[:-1]: d.setdefault(subkey, ConfigDict()) d = d[subkey] subkey = key_list[-1] d[subkey] = v cfg_dict = super().__getattribute__('_cfg_dict') super().__setattr__( '_cfg_dict', Config._merge_a_into_b( option_cfg_dict, cfg_dict, allow_list_keys=allow_list_keys)) @staticmethod def diff(cfg1: Union[str, 'Config'], cfg2: Union[str, 'Config']) -> str: if isinstance(cfg1, str): cfg1 = Config.fromfile(cfg1) if isinstance(cfg2, str): cfg2 = Config.fromfile(cfg2) res = difflib.unified_diff( cfg1.pretty_text.split('\n'), cfg2.pretty_text.split('\n')) # Convert into rich format for better visualization console = Console() text = Text() for line in res: if line.startswith('+'): color = 'bright_green' elif line.startswith('-'): color = 'bright_red' else: color = 'bright_white' _text = Text(line + '\n') _text.stylize(color) text.append(_text) with console.capture() as capture: console.print(text) return capture.get() @staticmethod def _is_lazy_import(filename: str) -> bool: if not filename.endswith('.py'): return False with open(filename, encoding='utf-8') as f: codes_str = f.read() parsed_codes = ast.parse(codes_str) for node in ast.walk(parsed_codes): if (isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) and node.targets[0].id == BASE_KEY): return False if isinstance(node, ast.With): expr = node.items[0].context_expr if (not isinstance(expr, ast.Call) or not expr.func.id == 'read_base'): # type: ignore raise ConfigParsingError( 'Only `read_base` context manager can be used in the ' 'config') return True if isinstance(node, ast.ImportFrom): # relative import -> lazy_import if node.level != 0: return True # Skip checking when using `mmengine.config` in cfg file if (node.module == 'mmengine' and len(node.names) == 1 and node.names[0].name == 'Config'): continue if not isinstance(node.module, str): continue # non-builtin module -> lazy_import if not _is_builtin_module(node.module): return True if isinstance(node, ast.Import): for alias_node in node.names: if not _is_builtin_module(alias_node.name): return True return False def _to_lazy_dict(self, keep_imported: bool = False) -> dict: """Convert config object to dictionary with lazy object, and filter the imported object.""" res = self._cfg_dict._to_lazy_dict() if hasattr(self, '_imported_names') and not keep_imported: res = { key: value for key, value in res.items() if key not in self._imported_names } return res def to_dict(self, keep_imported: bool = False): """Convert all data in the config to a builtin ``dict``. Args: keep_imported (bool): Whether to keep the imported field. Defaults to False If you import third-party objects in the config file, all imported objects will be converted to a string like ``torch.optim.SGD`` """ cfg_dict = self._cfg_dict.to_dict() if hasattr(self, '_imported_names') and not keep_imported: cfg_dict = { key: value for key, value in cfg_dict.items() if key not in self._imported_names } return cfg_dict
(cfg_dict: dict = None, cfg_text: Optional[str] = None, filename: Union[str, pathlib.Path, NoneType] = None, env_variables: Optional[dict] = None, format_python_code: bool = True)
729,995
mmengine.config.config
__copy__
null
def __copy__(self): cls = self.__class__ other = cls.__new__(cls) other.__dict__.update(self.__dict__) super(Config, other).__setattr__('_cfg_dict', self._cfg_dict.copy()) return other
(self)
729,996
mmengine.config.config
__deepcopy__
null
def __deepcopy__(self, memo): cls = self.__class__ other = cls.__new__(cls) memo[id(self)] = other for key, value in self.__dict__.items(): super(Config, other).__setattr__(key, copy.deepcopy(value, memo)) return other
(self, memo)
729,997
mmengine.config.config
__getattr__
null
def __getattr__(self, name: str) -> Any: return getattr(self._cfg_dict, name)
(self, name: str) -> Any
729,998
mmengine.config.config
__getitem__
null
def __getitem__(self, name): return self._cfg_dict.__getitem__(name)
(self, name)
729,999
mmengine.config.config
__getstate__
null
def __getstate__( self ) -> Tuple[dict, Optional[str], Optional[str], dict, bool, set]: state = (self._cfg_dict, self._filename, self._text, self._env_variables, self._format_python_code, self._imported_names) return state
(self) -> Tuple[dict, Optional[str], Optional[str], dict, bool, set]
730,000
mmengine.config.config
__init__
null
def __init__( self, cfg_dict: dict = None, cfg_text: Optional[str] = None, filename: Optional[Union[str, Path]] = None, env_variables: Optional[dict] = None, format_python_code: bool = True, ): filename = str(filename) if isinstance(filename, Path) else filename if cfg_dict is None: cfg_dict = dict() elif not isinstance(cfg_dict, dict): raise TypeError('cfg_dict must be a dict, but ' f'got {type(cfg_dict)}') for key in cfg_dict: if key in RESERVED_KEYS: raise KeyError(f'{key} is reserved for config file') if not isinstance(cfg_dict, ConfigDict): cfg_dict = ConfigDict(cfg_dict) super().__setattr__('_cfg_dict', cfg_dict) super().__setattr__('_filename', filename) super().__setattr__('_format_python_code', format_python_code) if not hasattr(self, '_imported_names'): super().__setattr__('_imported_names', set()) if cfg_text: text = cfg_text elif filename: with open(filename, encoding='utf-8') as f: text = f.read() else: text = '' super().__setattr__('_text', text) if env_variables is None: env_variables = dict() super().__setattr__('_env_variables', env_variables)
(self, cfg_dict: Optional[dict] = None, cfg_text: Optional[str] = None, filename: Union[str, pathlib.Path, NoneType] = None, env_variables: Optional[dict] = None, format_python_code: bool = True)
730,001
mmengine.config.config
__iter__
null
def __iter__(self): return iter(self._cfg_dict)
(self)
730,002
mmengine.config.config
__len__
null
def __len__(self): return len(self._cfg_dict)
(self)
730,003
mmengine.config.config
__repr__
null
def __repr__(self): return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}'
(self)
730,004
mmengine.config.config
__setattr__
null
def __setattr__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setattr__(name, value)
(self, name, value)
730,005
mmengine.config.config
__setitem__
null
def __setitem__(self, name, value): if isinstance(value, dict): value = ConfigDict(value) self._cfg_dict.__setitem__(name, value)
(self, name, value)
730,006
mmengine.config.config
__setstate__
null
def __setstate__(self, state: Tuple[dict, Optional[str], Optional[str], dict, bool, set]): super().__setattr__('_cfg_dict', state[0]) super().__setattr__('_filename', state[1]) super().__setattr__('_text', state[2]) super().__setattr__('_env_variables', state[3]) super().__setattr__('_format_python_code', state[4]) super().__setattr__('_imported_names', state[5])
(self, state: Tuple[dict, Optional[str], Optional[str], dict, bool, set])
730,007
mmengine.config.config
_dict_to_config_dict
Recursively converts ``dict`` to :obj:`ConfigDict`. Args: cfg (dict): Config dict. scope (str, optional): Scope of instance. has_scope (bool): Whether to add `_scope_` key to config dict. Returns: ConfigDict: Converted dict.
@staticmethod def _dict_to_config_dict(cfg: dict, scope: Optional[str] = None, has_scope=True): """Recursively converts ``dict`` to :obj:`ConfigDict`. Args: cfg (dict): Config dict. scope (str, optional): Scope of instance. has_scope (bool): Whether to add `_scope_` key to config dict. Returns: ConfigDict: Converted dict. """ # Only the outer dict with key `type` should have the key `_scope_`. if isinstance(cfg, dict): if has_scope and 'type' in cfg: has_scope = False if scope is not None and cfg.get('_scope_', None) is None: cfg._scope_ = scope # type: ignore cfg = ConfigDict(cfg) dict.__setattr__(cfg, 'scope', scope) for key, value in cfg.items(): cfg[key] = Config._dict_to_config_dict( value, scope=scope, has_scope=has_scope) elif isinstance(cfg, tuple): cfg = tuple( Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope) for _cfg in cfg) elif isinstance(cfg, list): cfg = [ Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope) for _cfg in cfg ] return cfg
(cfg: dict, scope: Optional[str] = None, has_scope=True)
730,008
mmengine.config.config
_dict_to_config_dict_lazy
Recursively converts ``dict`` to :obj:`ConfigDict`. The only difference between ``_dict_to_config_dict_lazy`` and ``_dict_to_config_dict_lazy`` is that the former one does not consider the scope, and will not trigger the building of ``LazyObject``. Args: cfg (dict): Config dict. Returns: ConfigDict: Converted dict.
@staticmethod def _dict_to_config_dict_lazy(cfg: dict): """Recursively converts ``dict`` to :obj:`ConfigDict`. The only difference between ``_dict_to_config_dict_lazy`` and ``_dict_to_config_dict_lazy`` is that the former one does not consider the scope, and will not trigger the building of ``LazyObject``. Args: cfg (dict): Config dict. Returns: ConfigDict: Converted dict. """ # Only the outer dict with key `type` should have the key `_scope_`. if isinstance(cfg, dict): cfg_dict = ConfigDict() for key, value in cfg.items(): cfg_dict[key] = Config._dict_to_config_dict_lazy(value) return cfg_dict if isinstance(cfg, (tuple, list)): return type(cfg)( Config._dict_to_config_dict_lazy(_cfg) for _cfg in cfg) return cfg
(cfg: dict)
730,009
mmengine.config.config
_file2dict
Transform file to variables dictionary. Args: filename (str): Name of config file. use_predefined_variables (bool, optional): Whether to use predefined variables. Defaults to True. use_environment_variables (bool, optional): Whether to use environment variables. Defaults to True. lazy_import (bool): Whether to load config in `lazy_import` mode. If it is `None`, it will be deduced by the content of the config file. Defaults to None. Returns: Tuple[dict, str]: Variables dictionary and text of Config.
@staticmethod def _file2dict( filename: str, use_predefined_variables: bool = True, use_environment_variables: bool = True, lazy_import: Optional[bool] = None) -> Tuple[dict, str, dict]: """Transform file to variables dictionary. Args: filename (str): Name of config file. use_predefined_variables (bool, optional): Whether to use predefined variables. Defaults to True. use_environment_variables (bool, optional): Whether to use environment variables. Defaults to True. lazy_import (bool): Whether to load config in `lazy_import` mode. If it is `None`, it will be deduced by the content of the config file. Defaults to None. Returns: Tuple[dict, str]: Variables dictionary and text of Config. """ if lazy_import is None and Config._is_lazy_import(filename): raise RuntimeError( 'The configuration file type in the inheritance chain ' 'must match the current configuration file type, either ' '"lazy_import" or non-"lazy_import". You got this error ' 'since you use the syntax like `with read_base(): ...` ' f'or import non-builtin module in {filename}. See more ' 'information in https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html' # noqa: E501 ) filename = osp.abspath(osp.expanduser(filename)) check_file_exist(filename) fileExtname = osp.splitext(filename)[1] if fileExtname not in ['.py', '.json', '.yaml', '.yml']: raise OSError('Only py/yml/yaml/json type are supported now!') try: with tempfile.TemporaryDirectory() as temp_config_dir: temp_config_file = tempfile.NamedTemporaryFile( dir=temp_config_dir, suffix=fileExtname, delete=False) if platform.system() == 'Windows': temp_config_file.close() # Substitute predefined variables if use_predefined_variables: Config._substitute_predefined_vars(filename, temp_config_file.name) else: shutil.copyfile(filename, temp_config_file.name) # Substitute environment variables env_variables = dict() if use_environment_variables: env_variables = Config._substitute_env_variables( temp_config_file.name, temp_config_file.name) # Substitute base variables from placeholders to strings base_var_dict = Config._pre_substitute_base_vars( temp_config_file.name, temp_config_file.name) # Handle base files base_cfg_dict = ConfigDict() cfg_text_list = list() for base_cfg_path in Config._get_base_files( temp_config_file.name): base_cfg_path, scope = Config._get_cfg_path( base_cfg_path, filename) _cfg_dict, _cfg_text, _env_variables = Config._file2dict( filename=base_cfg_path, use_predefined_variables=use_predefined_variables, use_environment_variables=use_environment_variables, lazy_import=lazy_import, ) cfg_text_list.append(_cfg_text) env_variables.update(_env_variables) duplicate_keys = base_cfg_dict.keys() & _cfg_dict.keys() if len(duplicate_keys) > 0: raise KeyError( 'Duplicate key is not allowed among bases. ' f'Duplicate keys: {duplicate_keys}') # _dict_to_config_dict will do the following things: # 1. Recursively converts ``dict`` to :obj:`ConfigDict`. # 2. Set `_scope_` for the outer dict variable for the base # config. # 3. Set `scope` attribute for each base variable. # Different from `_scope_`, `scope` is not a key of base # dict, `scope` attribute will be parsed to key `_scope_` # by function `_parse_scope` only if the base variable is # accessed by the current config. _cfg_dict = Config._dict_to_config_dict(_cfg_dict, scope) base_cfg_dict.update(_cfg_dict) if filename.endswith('.py'): with open(temp_config_file.name, encoding='utf-8') as f: parsed_codes = ast.parse(f.read()) parsed_codes = RemoveAssignFromAST(BASE_KEY).visit( parsed_codes) codeobj = compile(parsed_codes, filename, mode='exec') # Support load global variable in nested function of the # config. global_locals_var = {BASE_KEY: base_cfg_dict} ori_keys = set(global_locals_var.keys()) eval(codeobj, global_locals_var, global_locals_var) cfg_dict = { key: value for key, value in global_locals_var.items() if (key not in ori_keys and not key.startswith('__')) } elif filename.endswith(('.yml', '.yaml', '.json')): cfg_dict = load(temp_config_file.name) # close temp file for key, value in list(cfg_dict.items()): if isinstance(value, (types.FunctionType, types.ModuleType)): cfg_dict.pop(key) temp_config_file.close() # If the current config accesses a base variable of base # configs, The ``scope`` attribute of corresponding variable # will be converted to the `_scope_`. Config._parse_scope(cfg_dict) except Exception as e: if osp.exists(temp_config_dir): shutil.rmtree(temp_config_dir) raise e # check deprecation information if DEPRECATION_KEY in cfg_dict: deprecation_info = cfg_dict.pop(DEPRECATION_KEY) warning_msg = f'The config file {filename} will be deprecated ' \ 'in the future.' if 'expected' in deprecation_info: warning_msg += f' Please use {deprecation_info["expected"]} ' \ 'instead.' if 'reference' in deprecation_info: warning_msg += ' More information can be found at ' \ f'{deprecation_info["reference"]}' warnings.warn(warning_msg, DeprecationWarning) cfg_text = filename + '\n' with open(filename, encoding='utf-8') as f: # Setting encoding explicitly to resolve coding issue on windows cfg_text += f.read() # Substitute base variables from strings to their actual values cfg_dict = Config._substitute_base_vars(cfg_dict, base_var_dict, base_cfg_dict) cfg_dict.pop(BASE_KEY, None) cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict) cfg_dict = { k: v for k, v in cfg_dict.items() if not k.startswith('__') } # merge cfg_text cfg_text_list.append(cfg_text) cfg_text = '\n'.join(cfg_text_list) return cfg_dict, cfg_text, env_variables
(filename: str, use_predefined_variables: bool = True, use_environment_variables: bool = True, lazy_import: Optional[bool] = None) -> Tuple[dict, str, dict]
730,010
mmengine.config.config
_get_base_files
Get the base config file. Args: filename (str): The config file. Raises: TypeError: Name of config file. Returns: list: A list of base config.
@staticmethod def _get_base_files(filename: str) -> list: """Get the base config file. Args: filename (str): The config file. Raises: TypeError: Name of config file. Returns: list: A list of base config. """ file_format = osp.splitext(filename)[1] if file_format == '.py': Config._validate_py_syntax(filename) with open(filename, encoding='utf-8') as f: parsed_codes = ast.parse(f.read()).body def is_base_line(c): return (isinstance(c, ast.Assign) and isinstance(c.targets[0], ast.Name) and c.targets[0].id == BASE_KEY) base_code = next((c for c in parsed_codes if is_base_line(c)), None) if base_code is not None: base_code = ast.Expression( # type: ignore body=base_code.value) # type: ignore base_files = eval(compile(base_code, '', mode='eval')) else: base_files = [] elif file_format in ('.yml', '.yaml', '.json'): import mmengine cfg_dict = mmengine.load(filename) base_files = cfg_dict.get(BASE_KEY, []) else: raise ConfigParsingError( 'The config type should be py, json, yaml or ' f'yml, but got {file_format}') base_files = base_files if isinstance(base_files, list) else [base_files] return base_files
(filename: str) -> list
730,011
mmengine.config.config
_get_base_modules
Get base module name from parsed code. Args: nodes (list): Parsed code of the config file. Returns: list: Name of base modules.
@staticmethod def _get_base_modules(nodes: list) -> list: """Get base module name from parsed code. Args: nodes (list): Parsed code of the config file. Returns: list: Name of base modules. """ def _get_base_module_from_with(with_nodes: list) -> list: """Get base module name from if statement in python file. Args: with_nodes (list): List of if statement. Returns: list: Name of base modules. """ base_modules = [] for node in with_nodes: assert isinstance(node, ast.ImportFrom), ( 'Illegal syntax in config file! Only ' '`from ... import ...` could be implemented` in ' 'with read_base()`') assert node.module is not None, ( 'Illegal syntax in config file! Syntax like ' '`from . import xxx` is not allowed in `with read_base()`') base_modules.append(node.level * '.' + node.module) return base_modules for idx, node in enumerate(nodes): if (isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) and node.targets[0].id == BASE_KEY): raise ConfigParsingError( 'The configuration file type in the inheritance chain ' 'must match the current configuration file type, either ' '"lazy_import" or non-"lazy_import". You got this error ' f'since you use the syntax like `_base_ = "{node.targets[0].id}"` ' # noqa: E501 'in your config. You should use `with read_base(): ... to` ' # noqa: E501 'mark the inherited config file. See more information ' 'in https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html' # noqa: E501 ) if not isinstance(node, ast.With): continue expr = node.items[0].context_expr if (not isinstance(expr, ast.Call) or not expr.func.id == 'read_base' or # type: ignore len(node.items) > 1): raise ConfigParsingError( 'Only `read_base` context manager can be used in the ' 'config') # The original code: # ``` # with read_base(): # from .._base_.default_runtime import * # ``` # The processed code: # ``` # from .._base_.default_runtime import * # ``` # As you can see, the if statement is removed and the # from ... import statement will be unindent for nested_idx, nested_node in enumerate(node.body): nodes.insert(idx + nested_idx + 1, nested_node) nodes.pop(idx) return _get_base_module_from_with(node.body) return []
(nodes: list) -> list
730,012
mmengine.config.config
_get_cfg_path
Get the config path from the current or external package. Args: cfg_path (str): Relative path of config. filename (str): The config file being parsed. Returns: Tuple[str, str or None]: Path and scope of config. If the config is not an external config, the scope will be `None`.
@staticmethod def _get_cfg_path(cfg_path: str, filename: str) -> Tuple[str, Optional[str]]: """Get the config path from the current or external package. Args: cfg_path (str): Relative path of config. filename (str): The config file being parsed. Returns: Tuple[str, str or None]: Path and scope of config. If the config is not an external config, the scope will be `None`. """ if '::' in cfg_path: # `cfg_path` startswith '::' means an external config path. # Get package name and relative config path. scope = cfg_path.partition('::')[0] package, cfg_path = _get_package_and_cfg_path(cfg_path) if not is_installed(package): raise ModuleNotFoundError( f'{package} is not installed, please install {package} ' f'manually') # Get installed package path. package_path = get_installed_path(package) try: # Get config path from meta file. cfg_path = _get_external_cfg_path(package_path, cfg_path) except ValueError: # Since base config does not have a metafile, it should be # concatenated with package path and relative config path. cfg_path = _get_external_cfg_base_path(package_path, cfg_path) except FileNotFoundError as e: raise e return cfg_path, scope else: # Get local config path. cfg_dir = osp.dirname(filename) cfg_path = osp.join(cfg_dir, cfg_path) return cfg_path, None
(cfg_path: str, filename: str) -> Tuple[str, Optional[str]]
730,013
mmengine.config.config
_is_lazy_import
null
@staticmethod def _is_lazy_import(filename: str) -> bool: if not filename.endswith('.py'): return False with open(filename, encoding='utf-8') as f: codes_str = f.read() parsed_codes = ast.parse(codes_str) for node in ast.walk(parsed_codes): if (isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) and node.targets[0].id == BASE_KEY): return False if isinstance(node, ast.With): expr = node.items[0].context_expr if (not isinstance(expr, ast.Call) or not expr.func.id == 'read_base'): # type: ignore raise ConfigParsingError( 'Only `read_base` context manager can be used in the ' 'config') return True if isinstance(node, ast.ImportFrom): # relative import -> lazy_import if node.level != 0: return True # Skip checking when using `mmengine.config` in cfg file if (node.module == 'mmengine' and len(node.names) == 1 and node.names[0].name == 'Config'): continue if not isinstance(node.module, str): continue # non-builtin module -> lazy_import if not _is_builtin_module(node.module): return True if isinstance(node, ast.Import): for alias_node in node.names: if not _is_builtin_module(alias_node.name): return True return False
(filename: str) -> bool
730,014
mmengine.config.config
_merge_a_into_b
merge dict ``a`` into dict ``b`` (non-inplace). Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid in-place modifications. Args: a (dict): The source dict to be merged into ``b``. b (dict): The origin dict to be fetch keys from ``a``. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in source ``a`` and will replace the element of the corresponding index in b if b is a list. Defaults to False. Returns: dict: The modified dict of ``b`` using ``a``. Examples: # Normally merge a into b. >>> Config._merge_a_into_b( ... dict(obj=dict(a=2)), dict(obj=dict(a=1))) {'obj': {'a': 2}} # Delete b first and merge a into b. >>> Config._merge_a_into_b( ... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1))) {'obj': {'a': 2}} # b is a list >>> Config._merge_a_into_b( ... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True) [{'a': 2}, {'b': 2}]
@staticmethod def _merge_a_into_b(a: dict, b: dict, allow_list_keys: bool = False) -> dict: """merge dict ``a`` into dict ``b`` (non-inplace). Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid in-place modifications. Args: a (dict): The source dict to be merged into ``b``. b (dict): The origin dict to be fetch keys from ``a``. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in source ``a`` and will replace the element of the corresponding index in b if b is a list. Defaults to False. Returns: dict: The modified dict of ``b`` using ``a``. Examples: # Normally merge a into b. >>> Config._merge_a_into_b( ... dict(obj=dict(a=2)), dict(obj=dict(a=1))) {'obj': {'a': 2}} # Delete b first and merge a into b. >>> Config._merge_a_into_b( ... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1))) {'obj': {'a': 2}} # b is a list >>> Config._merge_a_into_b( ... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True) [{'a': 2}, {'b': 2}] """ b = b.copy() for k, v in a.items(): if allow_list_keys and k.isdigit() and isinstance(b, list): k = int(k) if len(b) <= k: raise KeyError(f'Index {k} exceeds the length of list {b}') b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys) elif isinstance(v, dict): if k in b and not v.pop(DELETE_KEY, False): allowed_types: Union[Tuple, type] = ( dict, list) if allow_list_keys else dict if not isinstance(b[k], allowed_types): raise TypeError( f'{k}={v} in child config cannot inherit from ' f'base because {k} is a dict in the child config ' f'but is of type {type(b[k])} in base config. ' f'You may set `{DELETE_KEY}=True` to ignore the ' f'base config.') b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys) else: b[k] = ConfigDict(v) else: b[k] = v return b
(a: dict, b: dict, allow_list_keys: bool = False) -> dict
730,015
mmengine.config.config
_parse_lazy_import
Transform file to variables dictionary. Args: filename (str): Name of config file. Returns: Tuple[dict, dict]: ``cfg_dict`` and ``imported_names``. - cfg_dict (dict): Variables dictionary of parsed config. - imported_names (set): Used to mark the names of imported object.
@staticmethod def _parse_lazy_import(filename: str) -> Tuple[ConfigDict, set]: """Transform file to variables dictionary. Args: filename (str): Name of config file. Returns: Tuple[dict, dict]: ``cfg_dict`` and ``imported_names``. - cfg_dict (dict): Variables dictionary of parsed config. - imported_names (set): Used to mark the names of imported object. """ # In lazy import mode, users can use the Python syntax `import` to # implement inheritance between configuration files, which is easier # for users to understand the hierarchical relationships between # different configuration files. # Besides, users can also using `import` syntax to import corresponding # module which will be filled in the `type` field. It means users # can directly navigate to the source of the module in the # configuration file by clicking the `type` field. # To avoid really importing the third party package like `torch` # during import `type` object, we use `_parse_lazy_import` to parse the # configuration file, which will not actually trigger the import # process, but simply parse the imported `type`s as LazyObject objects. # The overall pipeline of _parse_lazy_import is: # 1. Parse the base module from the config file. # || # \/ # base_module = ['mmdet.configs.default_runtime'] # || # \/ # 2. recursively parse the base module and gather imported objects to # a dict. # || # \/ # The base_dict will be: # { # 'mmdet.configs.default_runtime': {...} # 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...} # ... # }, each item in base_dict is a dict of `LazyObject` # 3. parse the current config file filling the imported variable # with the base_dict. # # 4. During the parsing process, all imported variable will be # recorded in the `imported_names` set. These variables can be # accessed, but will not be dumped by default. with open(filename, encoding='utf-8') as f: global_dict = {'LazyObject': LazyObject, '__file__': filename} base_dict = {} parsed_codes = ast.parse(f.read()) # get the names of base modules, and remove the # `with read_base():'` statement base_modules = Config._get_base_modules(parsed_codes.body) base_imported_names = set() for base_module in base_modules: # If base_module means a relative import, assuming the level is # 2, which means the module is imported like # "from ..a.b import c". we must ensure that c is an # object `defined` in module b, and module b should not be a # package including `__init__` file but a single python file. level = len(re.match(r'\.*', base_module).group()) if level > 0: # Relative import base_dir = osp.dirname(filename) module_path = osp.join( base_dir, *(['..'] * (level - 1)), f'{base_module[level:].replace(".", "/")}.py') else: # Absolute import module_list = base_module.split('.') if len(module_list) == 1: raise ConfigParsingError( 'The imported configuration file should not be ' f'an independent package {module_list[0]}. Here ' 'is an example: ' '`with read_base(): from mmdet.configs.retinanet_r50_fpn_1x_coco import *`' # noqa: E501 ) else: package = module_list[0] root_path = get_installed_path(package) module_path = f'{osp.join(root_path, *module_list[1:])}.py' # noqa: E501 if not osp.isfile(module_path): raise ConfigParsingError( f'{module_path} not found! It means that incorrect ' 'module is defined in ' f'`with read_base(): = from {base_module} import ...`, please ' # noqa: E501 'make sure the base config module is valid ' 'and is consistent with the prior import ' 'logic') _base_cfg_dict, _base_imported_names = Config._parse_lazy_import( # noqa: E501 module_path) base_imported_names |= _base_imported_names # The base_dict will be: # { # 'mmdet.configs.default_runtime': {...} # 'mmdet.configs.retinanet_r50_fpn_1x_coco': {...} # ... # } base_dict[base_module] = _base_cfg_dict # `base_dict` contains all the imported modules from `base_cfg`. # In order to collect the specific imported module from `base_cfg` # before parse the current file, we using AST Transform to # transverse the imported module from base_cfg and merge then into # the global dict. After the ast transformation, most of import # syntax will be removed (except for the builtin import) and # replaced with the `LazyObject` transform = ImportTransformer( global_dict=global_dict, base_dict=base_dict, filename=filename) modified_code = transform.visit(parsed_codes) modified_code, abs_imported = _gather_abs_import_lazyobj( modified_code, filename=filename) imported_names = transform.imported_obj | abs_imported imported_names |= base_imported_names modified_code = ast.fix_missing_locations(modified_code) exec( compile(modified_code, filename, mode='exec'), global_dict, global_dict) ret: dict = {} for key, value in global_dict.items(): if key.startswith('__') or key in ['LazyObject']: continue ret[key] = value # convert dict to ConfigDict cfg_dict = Config._dict_to_config_dict_lazy(ret) return cfg_dict, imported_names
(filename: str) -> Tuple[mmengine.config.config.ConfigDict, set]
730,016
mmengine.config.config
_parse_scope
Adds ``_scope_`` to :obj:`ConfigDict` instance, which means a base variable. If the config dict already has the scope, scope will not be overwritten. Args: cfg (dict): Config needs to be parsed with scope.
@staticmethod def _parse_scope(cfg: dict) -> None: """Adds ``_scope_`` to :obj:`ConfigDict` instance, which means a base variable. If the config dict already has the scope, scope will not be overwritten. Args: cfg (dict): Config needs to be parsed with scope. """ if isinstance(cfg, ConfigDict): cfg._scope_ = cfg.scope elif isinstance(cfg, (tuple, list)): [Config._parse_scope(value) for value in cfg] else: return
(cfg: dict) -> NoneType
730,017
mmengine.config.config
_pre_substitute_base_vars
Preceding step for substituting variables in base config with actual value. Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. Returns: dict: A dictionary contains variables in base config.
@staticmethod def _pre_substitute_base_vars(filename: str, temp_config_name: str) -> dict: """Preceding step for substituting variables in base config with actual value. Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. Returns: dict: A dictionary contains variables in base config. """ with open(filename, encoding='utf-8') as f: config_file = f.read() base_var_dict = {} regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}' base_vars = set(re.findall(regexp, config_file)) for base_var in base_vars: randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}' base_var_dict[randstr] = base_var regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}' config_file = re.sub(regexp, f'"{randstr}"', config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) return base_var_dict
(filename: str, temp_config_name: str) -> dict
730,018
mmengine.config.config
_substitute_base_vars
Substitute base variables from strings to their actual values. Args: Any : Config dictionary. base_var_dict (dict): A dictionary contains variables in base config. base_cfg (dict): Base config dictionary. Returns: Any : A dictionary with origin base variables substituted with actual values.
@staticmethod def _substitute_base_vars(cfg: Any, base_var_dict: dict, base_cfg: dict) -> Any: """Substitute base variables from strings to their actual values. Args: Any : Config dictionary. base_var_dict (dict): A dictionary contains variables in base config. base_cfg (dict): Base config dictionary. Returns: Any : A dictionary with origin base variables substituted with actual values. """ cfg = copy.deepcopy(cfg) if isinstance(cfg, dict): for k, v in cfg.items(): if isinstance(v, str) and v in base_var_dict: new_v = base_cfg for new_k in base_var_dict[v].split('.'): new_v = new_v[new_k] cfg[k] = new_v elif isinstance(v, (list, tuple, dict)): cfg[k] = Config._substitute_base_vars( v, base_var_dict, base_cfg) elif isinstance(cfg, tuple): cfg = tuple( Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg) elif isinstance(cfg, list): cfg = [ Config._substitute_base_vars(c, base_var_dict, base_cfg) for c in cfg ] elif isinstance(cfg, str) and cfg in base_var_dict: new_v = base_cfg for new_k in base_var_dict[cfg].split('.'): new_v = new_v[new_k] cfg = new_v return cfg
(cfg: Any, base_var_dict: dict, base_cfg: dict) -> Any
730,019
mmengine.config.config
_substitute_env_variables
Substitute environment variables in config with actual values. Sometimes, we want to change some items in the config with environment variables. For examples, we expect to change dataset root by setting ``DATASET_ROOT=/dataset/root/path`` in the command line. This can be easily achieved by writing lines in the config as follows .. code-block:: python data_root = '{{$DATASET_ROOT:/default/dataset}}/images' Here, ``{{$DATASET_ROOT:/default/dataset}}`` indicates using the environment variable ``DATASET_ROOT`` to replace the part between ``{{}}``. If the ``DATASET_ROOT`` is not set, the default value ``/default/dataset`` will be used. Environment variables not only can replace items in the string, they can also substitute other types of data in config. In this situation, we can write the config as below .. code-block:: python model = dict( bbox_head = dict(num_classes={{'$NUM_CLASSES:80'}})) For details, Please refer to docs/zh_cn/tutorials/config.md . Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config.
@staticmethod def _substitute_env_variables(filename: str, temp_config_name: str): """Substitute environment variables in config with actual values. Sometimes, we want to change some items in the config with environment variables. For examples, we expect to change dataset root by setting ``DATASET_ROOT=/dataset/root/path`` in the command line. This can be easily achieved by writing lines in the config as follows .. code-block:: python data_root = '{{$DATASET_ROOT:/default/dataset}}/images' Here, ``{{$DATASET_ROOT:/default/dataset}}`` indicates using the environment variable ``DATASET_ROOT`` to replace the part between ``{{}}``. If the ``DATASET_ROOT`` is not set, the default value ``/default/dataset`` will be used. Environment variables not only can replace items in the string, they can also substitute other types of data in config. In this situation, we can write the config as below .. code-block:: python model = dict( bbox_head = dict(num_classes={{'$NUM_CLASSES:80'}})) For details, Please refer to docs/zh_cn/tutorials/config.md . Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. """ with open(filename, encoding='utf-8') as f: config_file = f.read() regexp = r'\{\{[\'\"]?\s*\$(\w+)\s*\:\s*(\S*?)\s*[\'\"]?\}\}' keys = re.findall(regexp, config_file) env_variables = dict() for var_name, value in keys: regexp = r'\{\{[\'\"]?\s*\$' + var_name + r'\s*\:\s*' \ + value + r'\s*[\'\"]?\}\}' if var_name in os.environ: value = os.environ[var_name] env_variables[var_name] = value print_log( f'Using env variable `{var_name}` with value of ' f'{value} to replace item in config.', logger='current') if not value: raise KeyError(f'`{var_name}` cannot be found in `os.environ`.' f' Please set `{var_name}` in environment or ' 'give a default value.') config_file = re.sub(regexp, value, config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file) return env_variables
(filename: str, temp_config_name: str)
730,020
mmengine.config.config
_substitute_predefined_vars
Substitute predefined variables in config with actual values. Sometimes we want some variables in the config to be related to the current path or file name, etc. Here is an example of a typical usage scenario. When training a model, we define a working directory in the config that save the models and logs. For different configs, we expect to define different working directories. A common way for users is to use the config file name directly as part of the working directory name, e.g. for the config ``config_setting1.py``, the working directory is ``. /work_dir/config_setting1``. This can be easily achieved using predefined variables, which can be written in the config `config_setting1.py` as follows .. code-block:: python work_dir = '. /work_dir/{{ fileBasenameNoExtension }}' Here `{{ fileBasenameNoExtension }}` indicates the file name of the config (without the extension), and when the config class reads the config file, it will automatically parse this double-bracketed string to the corresponding actual value. .. code-block:: python cfg = Config.fromfile('. /config_setting1.py') cfg.work_dir # ". /work_dir/config_setting1" For details, Please refer to docs/zh_cn/advanced_tutorials/config.md . Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config.
@staticmethod def _substitute_predefined_vars(filename: str, temp_config_name: str): """Substitute predefined variables in config with actual values. Sometimes we want some variables in the config to be related to the current path or file name, etc. Here is an example of a typical usage scenario. When training a model, we define a working directory in the config that save the models and logs. For different configs, we expect to define different working directories. A common way for users is to use the config file name directly as part of the working directory name, e.g. for the config ``config_setting1.py``, the working directory is ``. /work_dir/config_setting1``. This can be easily achieved using predefined variables, which can be written in the config `config_setting1.py` as follows .. code-block:: python work_dir = '. /work_dir/{{ fileBasenameNoExtension }}' Here `{{ fileBasenameNoExtension }}` indicates the file name of the config (without the extension), and when the config class reads the config file, it will automatically parse this double-bracketed string to the corresponding actual value. .. code-block:: python cfg = Config.fromfile('. /config_setting1.py') cfg.work_dir # ". /work_dir/config_setting1" For details, Please refer to docs/zh_cn/advanced_tutorials/config.md . Args: filename (str): Filename of config. temp_config_name (str): Temporary filename to save substituted config. """ file_dirname = osp.dirname(filename) file_basename = osp.basename(filename) file_basename_no_extension = osp.splitext(file_basename)[0] file_extname = osp.splitext(filename)[1] support_templates = dict( fileDirname=file_dirname, fileBasename=file_basename, fileBasenameNoExtension=file_basename_no_extension, fileExtname=file_extname) with open(filename, encoding='utf-8') as f: config_file = f.read() for key, value in support_templates.items(): regexp = r'\{\{\s*' + str(key) + r'\s*\}\}' value = value.replace('\\', '/') config_file = re.sub(regexp, value, config_file) with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file: tmp_config_file.write(config_file)
(filename: str, temp_config_name: str)
730,021
mmengine.config.config
_to_lazy_dict
Convert config object to dictionary with lazy object, and filter the imported object.
def _to_lazy_dict(self, keep_imported: bool = False) -> dict: """Convert config object to dictionary with lazy object, and filter the imported object.""" res = self._cfg_dict._to_lazy_dict() if hasattr(self, '_imported_names') and not keep_imported: res = { key: value for key, value in res.items() if key not in self._imported_names } return res
(self, keep_imported: bool = False) -> dict
730,022
mmengine.config.config
_validate_py_syntax
Validate syntax of python config. Args: filename (str): Filename of python config file.
@staticmethod def _validate_py_syntax(filename: str): """Validate syntax of python config. Args: filename (str): Filename of python config file. """ with open(filename, encoding='utf-8') as f: content = f.read() try: ast.parse(content) except SyntaxError as e: raise SyntaxError('There are syntax errors in config ' f'file {filename}: {e}')
(filename: str)
730,023
mmengine.config.config
auto_argparser
Generate argparser from config file automatically (experimental)
@staticmethod def auto_argparser(description=None): """Generate argparser from config file automatically (experimental)""" partial_parser = ArgumentParser(description=description) partial_parser.add_argument('config', help='config file path') cfg_file = partial_parser.parse_known_args()[0].config cfg = Config.fromfile(cfg_file) parser = ArgumentParser(description=description) parser.add_argument('config', help='config file path') add_args(parser, cfg) return parser, cfg
(description=None)
730,025
mmengine.config.config
diff
null
@staticmethod def diff(cfg1: Union[str, 'Config'], cfg2: Union[str, 'Config']) -> str: if isinstance(cfg1, str): cfg1 = Config.fromfile(cfg1) if isinstance(cfg2, str): cfg2 = Config.fromfile(cfg2) res = difflib.unified_diff( cfg1.pretty_text.split('\n'), cfg2.pretty_text.split('\n')) # Convert into rich format for better visualization console = Console() text = Text() for line in res: if line.startswith('+'): color = 'bright_green' elif line.startswith('-'): color = 'bright_red' else: color = 'bright_white' _text = Text(line + '\n') _text.stylize(color) text.append(_text) with console.capture() as capture: console.print(text) return capture.get()
(cfg1: Union[str, mmengine.config.config.Config], cfg2: Union[str, mmengine.config.config.Config]) -> str
730,026
mmengine.config.config
dump
Dump config to file or return config text. Args: file (str or Path, optional): If not specified, then the object is dumped to a str, otherwise to a file specified by the filename. Defaults to None. Returns: str or None: Config text.
def dump(self, file: Optional[Union[str, Path]] = None): """Dump config to file or return config text. Args: file (str or Path, optional): If not specified, then the object is dumped to a str, otherwise to a file specified by the filename. Defaults to None. Returns: str or None: Config text. """ file = str(file) if isinstance(file, Path) else file cfg_dict = self.to_dict() if file is None: if self.filename is None or self.filename.endswith('.py'): return self.pretty_text else: file_format = self.filename.split('.')[-1] return dump(cfg_dict, file_format=file_format) elif file.endswith('.py'): with open(file, 'w', encoding='utf-8') as f: f.write(self.pretty_text) else: file_format = file.split('.')[-1] return dump(cfg_dict, file=file, file_format=file_format)
(self, file: Union[str, pathlib.Path, NoneType] = None)
730,027
mmengine.config.config
fromfile
Build a Config instance from config file. Args: filename (str or Path): Name of config file. use_predefined_variables (bool, optional): Whether to use predefined variables. Defaults to True. import_custom_modules (bool, optional): Whether to support importing custom modules in config. Defaults to None. use_environment_variables (bool, optional): Whether to use environment variables. Defaults to True. lazy_import (bool): Whether to load config in `lazy_import` mode. If it is `None`, it will be deduced by the content of the config file. Defaults to None. format_python_code (bool): Whether to format Python code by yapf. Defaults to True. Returns: Config: Config instance built from config file.
@staticmethod def fromfile(filename: Union[str, Path], use_predefined_variables: bool = True, import_custom_modules: bool = True, use_environment_variables: bool = True, lazy_import: Optional[bool] = None, format_python_code: bool = True) -> 'Config': """Build a Config instance from config file. Args: filename (str or Path): Name of config file. use_predefined_variables (bool, optional): Whether to use predefined variables. Defaults to True. import_custom_modules (bool, optional): Whether to support importing custom modules in config. Defaults to None. use_environment_variables (bool, optional): Whether to use environment variables. Defaults to True. lazy_import (bool): Whether to load config in `lazy_import` mode. If it is `None`, it will be deduced by the content of the config file. Defaults to None. format_python_code (bool): Whether to format Python code by yapf. Defaults to True. Returns: Config: Config instance built from config file. """ filename = str(filename) if isinstance(filename, Path) else filename if lazy_import is False or \ lazy_import is None and not Config._is_lazy_import(filename): cfg_dict, cfg_text, env_variables = Config._file2dict( filename, use_predefined_variables, use_environment_variables, lazy_import) if import_custom_modules and cfg_dict.get('custom_imports', None): try: import_modules_from_strings(**cfg_dict['custom_imports']) except ImportError as e: err_msg = ( 'Failed to import custom modules from ' f"{cfg_dict['custom_imports']}, the current sys.path " 'is: ') for p in sys.path: err_msg += f'\n {p}' err_msg += ( '\nYou should set `PYTHONPATH` to make `sys.path` ' 'include the directory which contains your custom ' 'module') raise ImportError(err_msg) from e return Config( cfg_dict, cfg_text=cfg_text, filename=filename, env_variables=env_variables, ) else: # Enable lazy import when parsing the config. # Using try-except to make sure ``ConfigDict.lazy`` will be reset # to False. See more details about lazy in the docstring of # ConfigDict ConfigDict.lazy = True try: cfg_dict, imported_names = Config._parse_lazy_import(filename) except Exception as e: raise e finally: # disable lazy import to get the real type. See more details # about lazy in the docstring of ConfigDict ConfigDict.lazy = False cfg = Config( cfg_dict, filename=filename, format_python_code=format_python_code) object.__setattr__(cfg, '_imported_names', imported_names) return cfg
(filename: Union[str, pathlib.Path], use_predefined_variables: bool = True, import_custom_modules: bool = True, use_environment_variables: bool = True, lazy_import: Optional[bool] = None, format_python_code: bool = True) -> mmengine.config.config.Config
730,028
mmengine.config.config
fromstring
Build a Config instance from config text. Args: cfg_str (str): Config text. file_format (str): Config file format corresponding to the config str. Only py/yml/yaml/json type are supported now! Returns: Config: Config object generated from ``cfg_str``.
@staticmethod def fromstring(cfg_str: str, file_format: str) -> 'Config': """Build a Config instance from config text. Args: cfg_str (str): Config text. file_format (str): Config file format corresponding to the config str. Only py/yml/yaml/json type are supported now! Returns: Config: Config object generated from ``cfg_str``. """ if file_format not in ['.py', '.json', '.yaml', '.yml']: raise OSError('Only py/yml/yaml/json type are supported now!') if file_format != '.py' and 'dict(' in cfg_str: # check if users specify a wrong suffix for python warnings.warn( 'Please check "file_format", the file format may be .py') # A temporary file can not be opened a second time on Windows. # See https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile for more details. # noqa # `temp_file` is opened first in `tempfile.NamedTemporaryFile` and # second in `Config.from_file`. # In addition, a named temporary file will be removed after closed. # As a workaround we set `delete=False` and close the temporary file # before opening again. with tempfile.NamedTemporaryFile( 'w', encoding='utf-8', suffix=file_format, delete=False) as temp_file: temp_file.write(cfg_str) cfg = Config.fromfile(temp_file.name) os.remove(temp_file.name) # manually delete the temporary file return cfg
(cfg_str: str, file_format: str) -> mmengine.config.config.Config
730,029
mmengine.config.config
merge_from_dict
Merge list into cfg_dict. Merge the dict parsed by MultipleKVAction into this cfg. Args: options (dict): dict of configs to merge from. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in ``options`` and will replace the element of the corresponding index in the config if the config is a list. Defaults to True. Examples: >>> from mmengine import Config >>> # Merge dictionary element >>> options = {'model.backbone.depth': 50, 'model.backbone.with_cp': True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg._cfg_dict {'model': {'backbone': {'type': 'ResNet', 'depth': 50, 'with_cp': True}}} >>> # Merge list element >>> cfg = Config( >>> dict(pipeline=[dict(type='LoadImage'), >>> dict(type='LoadAnnotations')])) >>> options = dict(pipeline={'0': dict(type='SelfLoadImage')}) >>> cfg.merge_from_dict(options, allow_list_keys=True) >>> cfg._cfg_dict {'pipeline': [{'type': 'SelfLoadImage'}, {'type': 'LoadAnnotations'}]}
def merge_from_dict(self, options: dict, allow_list_keys: bool = True) -> None: """Merge list into cfg_dict. Merge the dict parsed by MultipleKVAction into this cfg. Args: options (dict): dict of configs to merge from. allow_list_keys (bool): If True, int string keys (e.g. '0', '1') are allowed in ``options`` and will replace the element of the corresponding index in the config if the config is a list. Defaults to True. Examples: >>> from mmengine import Config >>> # Merge dictionary element >>> options = {'model.backbone.depth': 50, 'model.backbone.with_cp': True} >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet')))) >>> cfg.merge_from_dict(options) >>> cfg._cfg_dict {'model': {'backbone': {'type': 'ResNet', 'depth': 50, 'with_cp': True}}} >>> # Merge list element >>> cfg = Config( >>> dict(pipeline=[dict(type='LoadImage'), >>> dict(type='LoadAnnotations')])) >>> options = dict(pipeline={'0': dict(type='SelfLoadImage')}) >>> cfg.merge_from_dict(options, allow_list_keys=True) >>> cfg._cfg_dict {'pipeline': [{'type': 'SelfLoadImage'}, {'type': 'LoadAnnotations'}]} """ # noqa: E501 option_cfg_dict: dict = {} for full_key, v in options.items(): d = option_cfg_dict key_list = full_key.split('.') for subkey in key_list[:-1]: d.setdefault(subkey, ConfigDict()) d = d[subkey] subkey = key_list[-1] d[subkey] = v cfg_dict = super().__getattribute__('_cfg_dict') super().__setattr__( '_cfg_dict', Config._merge_a_into_b( option_cfg_dict, cfg_dict, allow_list_keys=allow_list_keys))
(self, options: dict, allow_list_keys: bool = True) -> NoneType
730,030
mmengine.config.config
to_dict
Convert all data in the config to a builtin ``dict``. Args: keep_imported (bool): Whether to keep the imported field. Defaults to False If you import third-party objects in the config file, all imported objects will be converted to a string like ``torch.optim.SGD``
def to_dict(self, keep_imported: bool = False): """Convert all data in the config to a builtin ``dict``. Args: keep_imported (bool): Whether to keep the imported field. Defaults to False If you import third-party objects in the config file, all imported objects will be converted to a string like ``torch.optim.SGD`` """ cfg_dict = self._cfg_dict.to_dict() if hasattr(self, '_imported_names') and not keep_imported: cfg_dict = { key: value for key, value in cfg_dict.items() if key not in self._imported_names } return cfg_dict
(self, keep_imported: bool = False)
730,031
mmengine.config.config
ConfigDict
A dictionary for config which has the same interface as python's built- in dictionary and can be used as a normal dictionary. The Config class would transform the nested fields (dictionary-like fields) in config file into ``ConfigDict``. If the class attribute ``lazy`` is ``False``, users will get the object built by ``LazyObject`` or ``LazyAttr``, otherwise users will get the ``LazyObject`` or ``LazyAttr`` itself. The ``lazy`` should be set to ``True`` to avoid building the imported object during configuration parsing, and it should be set to False outside the Config to ensure that users do not experience the ``LazyObject``.
class ConfigDict(Dict): """A dictionary for config which has the same interface as python's built- in dictionary and can be used as a normal dictionary. The Config class would transform the nested fields (dictionary-like fields) in config file into ``ConfigDict``. If the class attribute ``lazy`` is ``False``, users will get the object built by ``LazyObject`` or ``LazyAttr``, otherwise users will get the ``LazyObject`` or ``LazyAttr`` itself. The ``lazy`` should be set to ``True`` to avoid building the imported object during configuration parsing, and it should be set to False outside the Config to ensure that users do not experience the ``LazyObject``. """ lazy = False def __init__(__self, *args, **kwargs): object.__setattr__(__self, '__parent', kwargs.pop('__parent', None)) object.__setattr__(__self, '__key', kwargs.pop('__key', None)) object.__setattr__(__self, '__frozen', False) for arg in args: if not arg: continue # Since ConfigDict.items will convert LazyObject to real object # automatically, we need to call super().items() to make sure # the LazyObject will not be converted. if isinstance(arg, ConfigDict): for key, val in dict.items(arg): __self[key] = __self._hook(val) elif isinstance(arg, dict): for key, val in arg.items(): __self[key] = __self._hook(val) elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)): __self[arg[0]] = __self._hook(arg[1]) else: for key, val in iter(arg): __self[key] = __self._hook(val) for key, val in dict.items(kwargs): __self[key] = __self._hook(val) def __missing__(self, name): raise KeyError(name) def __getattr__(self, name): try: value = super().__getattr__(name) if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy: value = value.build() except KeyError: raise AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'") except Exception as e: raise e else: return value @classmethod def _hook(cls, item): # avoid to convert user defined dict to ConfigDict. if type(item) in (dict, OrderedDict): return cls(item) elif isinstance(item, (list, tuple)): return type(item)(cls._hook(elem) for elem in item) return item def __setattr__(self, name, value): value = self._hook(value) return super().__setattr__(name, value) def __setitem__(self, name, value): value = self._hook(value) return super().__setitem__(name, value) def __getitem__(self, key): return self.build_lazy(super().__getitem__(key)) def __deepcopy__(self, memo): other = self.__class__() memo[id(self)] = other for key, value in super().items(): other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo) return other def __copy__(self): other = self.__class__() for key, value in super().items(): other[key] = value return other copy = __copy__ def __iter__(self): # Implement `__iter__` to overwrite the unpacking operator `**cfg_dict` # to get the built lazy object return iter(self.keys()) def get(self, key: str, default: Optional[Any] = None) -> Any: """Get the value of the key. If class attribute ``lazy`` is True, the LazyObject will be built and returned. Args: key (str): The key. default (any, optional): The default value. Defaults to None. Returns: Any: The value of the key. """ return self.build_lazy(super().get(key, default)) def pop(self, key, default=None): """Pop the value of the key. If class attribute ``lazy`` is True, the LazyObject will be built and returned. Args: key (str): The key. default (any, optional): The default value. Defaults to None. Returns: Any: The value of the key. """ return self.build_lazy(super().pop(key, default)) def update(self, *args, **kwargs) -> None: """Override this method to make sure the LazyObject will not be built during updating.""" other = {} if args: if len(args) > 1: raise TypeError('update only accept one positional argument') # Avoid to used self.items to build LazyObject for key, value in dict.items(args[0]): other[key] = value for key, value in dict(kwargs).items(): other[key] = value for k, v in other.items(): if ((k not in self) or (not isinstance(self[k], dict)) or (not isinstance(v, dict))): self[k] = self._hook(v) else: self[k].update(v) def build_lazy(self, value: Any) -> Any: """If class attribute ``lazy`` is False, the LazyObject will be built and returned. Args: value (Any): The value to be built. Returns: Any: The built value. """ if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy: value = value.build() return value def values(self): """Yield the values of the dictionary. If class attribute ``lazy`` is False, the value of ``LazyObject`` or ``LazyAttr`` will be built and returned. """ values = [] for value in super().values(): values.append(self.build_lazy(value)) return values def items(self): """Yield the keys and values of the dictionary. If class attribute ``lazy`` is False, the value of ``LazyObject`` or ``LazyAttr`` will be built and returned. """ items = [] for key, value in super().items(): items.append((key, self.build_lazy(value))) return items def merge(self, other: dict): """Merge another dictionary into current dictionary. Args: other (dict): Another dictionary. """ default = object() def _merge_a_into_b(a, b): if isinstance(a, dict): if not isinstance(b, dict): a.pop(DELETE_KEY, None) return a if a.pop(DELETE_KEY, False): b.clear() all_keys = list(b.keys()) + list(a.keys()) return { key: _merge_a_into_b(a.get(key, default), b.get(key, default)) for key in all_keys if key != DELETE_KEY } else: return a if a is not default else b merged = _merge_a_into_b(copy.deepcopy(other), copy.deepcopy(self)) self.clear() for key, value in merged.items(): self[key] = value def __reduce_ex__(self, proto): # Override __reduce_ex__ to avoid `self.items` will be # called by CPython interpreter during pickling. See more details in # https://github.com/python/cpython/blob/8d61a71f9c81619e34d4a30b625922ebc83c561b/Objects/typeobject.c#L6196 # noqa: E501 if digit_version(platform.python_version()) < digit_version('3.8'): return (self.__class__, ({k: v for k, v in super().items()}, ), None, None, None) else: return (self.__class__, ({k: v for k, v in super().items()}, ), None, None, None, None) def __eq__(self, other): if isinstance(other, ConfigDict): return other.to_dict() == self.to_dict() elif isinstance(other, dict): return {k: v for k, v in self.items()} == other else: return False def _to_lazy_dict(self): """Convert the ConfigDict to a normal dictionary recursively, and keep the ``LazyObject`` or ``LazyAttr`` object not built.""" def _to_dict(data): if isinstance(data, ConfigDict): return { key: _to_dict(value) for key, value in Dict.items(data) } elif isinstance(data, dict): return {key: _to_dict(value) for key, value in data.items()} elif isinstance(data, (list, tuple)): return type(data)(_to_dict(item) for item in data) else: return data return _to_dict(self) def to_dict(self): """Convert the ConfigDict to a normal dictionary recursively, and convert the ``LazyObject`` or ``LazyAttr`` to string.""" return _lazy2string(self, dict_type=dict)
(*args, **kwargs)
730,033
mmengine.config.config
__copy__
null
def __copy__(self): other = self.__class__() for key, value in super().items(): other[key] = value return other
(self)
730,034
mmengine.config.config
__deepcopy__
null
def __deepcopy__(self, memo): other = self.__class__() memo[id(self)] = other for key, value in super().items(): other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo) return other
(self, memo)
730,036
mmengine.config.config
__eq__
null
def __eq__(self, other): if isinstance(other, ConfigDict): return other.to_dict() == self.to_dict() elif isinstance(other, dict): return {k: v for k, v in self.items()} == other else: return False
(self, other)
730,037
mmengine.config.config
__getattr__
null
def __getattr__(self, name): try: value = super().__getattr__(name) if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy: value = value.build() except KeyError: raise AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'") except Exception as e: raise e else: return value
(self, name)
730,038
mmengine.config.config
__getitem__
null
def __getitem__(self, key): return self.build_lazy(super().__getitem__(key))
(self, key)
730,041
mmengine.config.config
__init__
null
def __init__(__self, *args, **kwargs): object.__setattr__(__self, '__parent', kwargs.pop('__parent', None)) object.__setattr__(__self, '__key', kwargs.pop('__key', None)) object.__setattr__(__self, '__frozen', False) for arg in args: if not arg: continue # Since ConfigDict.items will convert LazyObject to real object # automatically, we need to call super().items() to make sure # the LazyObject will not be converted. if isinstance(arg, ConfigDict): for key, val in dict.items(arg): __self[key] = __self._hook(val) elif isinstance(arg, dict): for key, val in arg.items(): __self[key] = __self._hook(val) elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)): __self[arg[0]] = __self._hook(arg[1]) else: for key, val in iter(arg): __self[key] = __self._hook(val) for key, val in dict.items(kwargs): __self[key] = __self._hook(val)
(_ConfigDict__self, *args, **kwargs)
730,043
mmengine.config.config
__iter__
null
def __iter__(self): # Implement `__iter__` to overwrite the unpacking operator `**cfg_dict` # to get the built lazy object return iter(self.keys())
(self)
730,044
mmengine.config.config
__missing__
null
def __missing__(self, name): raise KeyError(name)
(self, name)
730,046
mmengine.config.config
__reduce_ex__
null
def __reduce_ex__(self, proto): # Override __reduce_ex__ to avoid `self.items` will be # called by CPython interpreter during pickling. See more details in # https://github.com/python/cpython/blob/8d61a71f9c81619e34d4a30b625922ebc83c561b/Objects/typeobject.c#L6196 # noqa: E501 if digit_version(platform.python_version()) < digit_version('3.8'): return (self.__class__, ({k: v for k, v in super().items()}, ), None, None, None) else: return (self.__class__, ({k: v for k, v in super().items()}, ), None, None, None, None)
(self, proto)
730,048
mmengine.config.config
__setattr__
null
def __setattr__(self, name, value): value = self._hook(value) return super().__setattr__(name, value)
(self, name, value)
730,049
mmengine.config.config
__setitem__
null
def __setitem__(self, name, value): value = self._hook(value) return super().__setitem__(name, value)
(self, name, value)
730,051
mmengine.config.config
_to_lazy_dict
Convert the ConfigDict to a normal dictionary recursively, and keep the ``LazyObject`` or ``LazyAttr`` object not built.
def _to_lazy_dict(self): """Convert the ConfigDict to a normal dictionary recursively, and keep the ``LazyObject`` or ``LazyAttr`` object not built.""" def _to_dict(data): if isinstance(data, ConfigDict): return { key: _to_dict(value) for key, value in Dict.items(data) } elif isinstance(data, dict): return {key: _to_dict(value) for key, value in data.items()} elif isinstance(data, (list, tuple)): return type(data)(_to_dict(item) for item in data) else: return data return _to_dict(self)
(self)
730,052
mmengine.config.config
build_lazy
If class attribute ``lazy`` is False, the LazyObject will be built and returned. Args: value (Any): The value to be built. Returns: Any: The built value.
def build_lazy(self, value: Any) -> Any: """If class attribute ``lazy`` is False, the LazyObject will be built and returned. Args: value (Any): The value to be built. Returns: Any: The built value. """ if isinstance(value, (LazyAttr, LazyObject)) and not self.lazy: value = value.build() return value
(self, value: Any) -> Any
730,056
mmengine.config.config
get
Get the value of the key. If class attribute ``lazy`` is True, the LazyObject will be built and returned. Args: key (str): The key. default (any, optional): The default value. Defaults to None. Returns: Any: The value of the key.
def get(self, key: str, default: Optional[Any] = None) -> Any: """Get the value of the key. If class attribute ``lazy`` is True, the LazyObject will be built and returned. Args: key (str): The key. default (any, optional): The default value. Defaults to None. Returns: Any: The value of the key. """ return self.build_lazy(super().get(key, default))
(self, key: str, default: Optional[Any] = None) -> Any
730,057
mmengine.config.config
items
Yield the keys and values of the dictionary. If class attribute ``lazy`` is False, the value of ``LazyObject`` or ``LazyAttr`` will be built and returned.
def items(self): """Yield the keys and values of the dictionary. If class attribute ``lazy`` is False, the value of ``LazyObject`` or ``LazyAttr`` will be built and returned. """ items = [] for key, value in super().items(): items.append((key, self.build_lazy(value))) return items
(self)
730,058
mmengine.config.config
merge
Merge another dictionary into current dictionary. Args: other (dict): Another dictionary.
def merge(self, other: dict): """Merge another dictionary into current dictionary. Args: other (dict): Another dictionary. """ default = object() def _merge_a_into_b(a, b): if isinstance(a, dict): if not isinstance(b, dict): a.pop(DELETE_KEY, None) return a if a.pop(DELETE_KEY, False): b.clear() all_keys = list(b.keys()) + list(a.keys()) return { key: _merge_a_into_b(a.get(key, default), b.get(key, default)) for key in all_keys if key != DELETE_KEY } else: return a if a is not default else b merged = _merge_a_into_b(copy.deepcopy(other), copy.deepcopy(self)) self.clear() for key, value in merged.items(): self[key] = value
(self, other: dict)
730,059
mmengine.config.config
pop
Pop the value of the key. If class attribute ``lazy`` is True, the LazyObject will be built and returned. Args: key (str): The key. default (any, optional): The default value. Defaults to None. Returns: Any: The value of the key.
def pop(self, key, default=None): """Pop the value of the key. If class attribute ``lazy`` is True, the LazyObject will be built and returned. Args: key (str): The key. default (any, optional): The default value. Defaults to None. Returns: Any: The value of the key. """ return self.build_lazy(super().pop(key, default))
(self, key, default=None)
730,061
mmengine.config.config
to_dict
Convert the ConfigDict to a normal dictionary recursively, and convert the ``LazyObject`` or ``LazyAttr`` to string.
def to_dict(self): """Convert the ConfigDict to a normal dictionary recursively, and convert the ``LazyObject`` or ``LazyAttr`` to string.""" return _lazy2string(self, dict_type=dict)
(self)
730,063
mmengine.config.config
update
Override this method to make sure the LazyObject will not be built during updating.
def update(self, *args, **kwargs) -> None: """Override this method to make sure the LazyObject will not be built during updating.""" other = {} if args: if len(args) > 1: raise TypeError('update only accept one positional argument') # Avoid to used self.items to build LazyObject for key, value in dict.items(args[0]): other[key] = value for key, value in dict(kwargs).items(): other[key] = value for k, v in other.items(): if ((k not in self) or (not isinstance(self[k], dict)) or (not isinstance(v, dict))): self[k] = self._hook(v) else: self[k].update(v)
(self, *args, **kwargs) -> NoneType
730,064
mmengine.config.config
values
Yield the values of the dictionary. If class attribute ``lazy`` is False, the value of ``LazyObject`` or ``LazyAttr`` will be built and returned.
def values(self): """Yield the values of the dictionary. If class attribute ``lazy`` is False, the value of ``LazyObject`` or ``LazyAttr`` will be built and returned. """ values = [] for value in super().values(): values.append(self.build_lazy(value)) return values
(self)
730,065
mmengine.registry.default_scope
DefaultScope
Scope of current task used to reset the current registry, which can be accessed globally. Consider the case of resetting the current ``Registry`` by ``default_scope`` in the internal module which cannot access runner directly, it is difficult to get the ``default_scope`` defined in ``Runner``. However, if ``Runner`` created ``DefaultScope`` instance by given ``default_scope``, the internal module can get ``default_scope`` by ``DefaultScope.get_current_instance`` everywhere. Args: name (str): Name of default scope for global access. scope_name (str): Scope of current task. Examples: >>> from mmengine.model import MODELS >>> # Define default scope in runner. >>> DefaultScope.get_instance('task', scope_name='mmdet') >>> # Get default scope globally. >>> scope_name = DefaultScope.get_instance('task').scope_name
class DefaultScope(ManagerMixin): """Scope of current task used to reset the current registry, which can be accessed globally. Consider the case of resetting the current ``Registry`` by ``default_scope`` in the internal module which cannot access runner directly, it is difficult to get the ``default_scope`` defined in ``Runner``. However, if ``Runner`` created ``DefaultScope`` instance by given ``default_scope``, the internal module can get ``default_scope`` by ``DefaultScope.get_current_instance`` everywhere. Args: name (str): Name of default scope for global access. scope_name (str): Scope of current task. Examples: >>> from mmengine.model import MODELS >>> # Define default scope in runner. >>> DefaultScope.get_instance('task', scope_name='mmdet') >>> # Get default scope globally. >>> scope_name = DefaultScope.get_instance('task').scope_name """ def __init__(self, name: str, scope_name: str): super().__init__(name) assert isinstance( scope_name, str), (f'scope_name should be a string, but got {scope_name}') self._scope_name = scope_name @property def scope_name(self) -> str: """ Returns: str: Get current scope. """ return self._scope_name @classmethod def get_current_instance(cls) -> Optional['DefaultScope']: """Get latest created default scope. Since default_scope is an optional argument for ``Registry.build``. ``get_current_instance`` should return ``None`` if there is no ``DefaultScope`` created. Examples: >>> default_scope = DefaultScope.get_current_instance() >>> # There is no `DefaultScope` created yet, >>> # `get_current_instance` return `None`. >>> default_scope = DefaultScope.get_instance( >>> 'instance_name', scope_name='mmengine') >>> default_scope.scope_name mmengine >>> default_scope = DefaultScope.get_current_instance() >>> default_scope.scope_name mmengine Returns: Optional[DefaultScope]: Return None If there has not been ``DefaultScope`` instance created yet, otherwise return the latest created DefaultScope instance. """ _accquire_lock() if cls._instance_dict: instance = super().get_current_instance() else: instance = None _release_lock() return instance @classmethod @contextmanager def overwrite_default_scope(cls, scope_name: Optional[str]) -> Generator: """overwrite the current default scope with `scope_name`""" if scope_name is None: yield else: tmp = copy.deepcopy(cls._instance_dict) # To avoid create an instance with the same name. time.sleep(1e-6) cls.get_instance(f'overwrite-{time.time()}', scope_name=scope_name) try: yield finally: cls._instance_dict = tmp
(name: str, scope_name: str)
730,066
mmengine.registry.default_scope
__init__
null
def __init__(self, name: str, scope_name: str): super().__init__(name) assert isinstance( scope_name, str), (f'scope_name should be a string, but got {scope_name}') self._scope_name = scope_name
(self, name: str, scope_name: str)
730,067
mmengine.config.config
DictAction
argparse action to split an argument into KEY=VALUE form on the first = and append to a dictionary. List options can be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build list/tuple values. e.g. 'KEY=[(V1,V2),(V3,V4)]'
class DictAction(Action): """ argparse action to split an argument into KEY=VALUE form on the first = and append to a dictionary. List options can be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build list/tuple values. e.g. 'KEY=[(V1,V2),(V3,V4)]' """ @staticmethod def _parse_int_float_bool(val: str) -> Union[int, float, bool, Any]: """parse int/float/bool value in the string.""" try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass if val.lower() in ['true', 'false']: return True if val.lower() == 'true' else False if val == 'None': return None return val @staticmethod def _parse_iterable(val: str) -> Union[list, tuple, Any]: """Parse iterable values in the string. All elements inside '()' or '[]' are treated as iterable values. Args: val (str): Value string. Returns: list | tuple | Any: The expanded list or tuple from the string, or single value if no iterable values are found. Examples: >>> DictAction._parse_iterable('1,2,3') [1, 2, 3] >>> DictAction._parse_iterable('[a, b, c]') ['a', 'b', 'c'] >>> DictAction._parse_iterable('[(1, 2, 3), [a, b], c]') [(1, 2, 3), ['a', 'b'], 'c'] """ def find_next_comma(string): """Find the position of next comma in the string. If no ',' is found in the string, return the string length. All chars inside '()' and '[]' are treated as one element and thus ',' inside these brackets are ignored. """ assert (string.count('(') == string.count(')')) and ( string.count('[') == string.count(']')), \ f'Imbalanced brackets exist in {string}' end = len(string) for idx, char in enumerate(string): pre = string[:idx] # The string before this ',' is balanced if ((char == ',') and (pre.count('(') == pre.count(')')) and (pre.count('[') == pre.count(']'))): end = idx break return end # Strip ' and " characters and replace whitespace. val = val.strip('\'\"').replace(' ', '') is_tuple = False if val.startswith('(') and val.endswith(')'): is_tuple = True val = val[1:-1] elif val.startswith('[') and val.endswith(']'): val = val[1:-1] elif ',' not in val: # val is a single value return DictAction._parse_int_float_bool(val) values = [] while len(val) > 0: comma_idx = find_next_comma(val) element = DictAction._parse_iterable(val[:comma_idx]) values.append(element) val = val[comma_idx + 1:] if is_tuple: return tuple(values) return values def __call__(self, parser: ArgumentParser, namespace: Namespace, values: Union[str, Sequence[Any], None], option_string: str = None): """Parse Variables in string and add them into argparser. Args: parser (ArgumentParser): Argument parser. namespace (Namespace): Argument namespace. values (Union[str, Sequence[Any], None]): Argument string. option_string (list[str], optional): Option string. Defaults to None. """ # Copied behavior from `argparse._ExtendAction`. options = copy.copy(getattr(namespace, self.dest, None) or {}) if values is not None: for kv in values: key, val = kv.split('=', maxsplit=1) options[key] = self._parse_iterable(val) setattr(namespace, self.dest, options)
(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
730,068
mmengine.config.config
__call__
Parse Variables in string and add them into argparser. Args: parser (ArgumentParser): Argument parser. namespace (Namespace): Argument namespace. values (Union[str, Sequence[Any], None]): Argument string. option_string (list[str], optional): Option string. Defaults to None.
def __call__(self, parser: ArgumentParser, namespace: Namespace, values: Union[str, Sequence[Any], None], option_string: str = None): """Parse Variables in string and add them into argparser. Args: parser (ArgumentParser): Argument parser. namespace (Namespace): Argument namespace. values (Union[str, Sequence[Any], None]): Argument string. option_string (list[str], optional): Option string. Defaults to None. """ # Copied behavior from `argparse._ExtendAction`. options = copy.copy(getattr(namespace, self.dest, None) or {}) if values is not None: for kv in values: key, val = kv.split('=', maxsplit=1) options[key] = self._parse_iterable(val) setattr(namespace, self.dest, options)
(self, parser: argparse.ArgumentParser, namespace: argparse.Namespace, values: Union[str, Sequence[Any], NoneType], option_string: Optional[str] = None)
730,073
mmengine.config.config
_parse_int_float_bool
parse int/float/bool value in the string.
@staticmethod def _parse_int_float_bool(val: str) -> Union[int, float, bool, Any]: """parse int/float/bool value in the string.""" try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass if val.lower() in ['true', 'false']: return True if val.lower() == 'true' else False if val == 'None': return None return val
(val: str) -> Union[int, float, bool, Any]
730,074
mmengine.config.config
_parse_iterable
Parse iterable values in the string. All elements inside '()' or '[]' are treated as iterable values. Args: val (str): Value string. Returns: list | tuple | Any: The expanded list or tuple from the string, or single value if no iterable values are found. Examples: >>> DictAction._parse_iterable('1,2,3') [1, 2, 3] >>> DictAction._parse_iterable('[a, b, c]') ['a', 'b', 'c'] >>> DictAction._parse_iterable('[(1, 2, 3), [a, b], c]') [(1, 2, 3), ['a', 'b'], 'c']
@staticmethod def _parse_iterable(val: str) -> Union[list, tuple, Any]: """Parse iterable values in the string. All elements inside '()' or '[]' are treated as iterable values. Args: val (str): Value string. Returns: list | tuple | Any: The expanded list or tuple from the string, or single value if no iterable values are found. Examples: >>> DictAction._parse_iterable('1,2,3') [1, 2, 3] >>> DictAction._parse_iterable('[a, b, c]') ['a', 'b', 'c'] >>> DictAction._parse_iterable('[(1, 2, 3), [a, b], c]') [(1, 2, 3), ['a', 'b'], 'c'] """ def find_next_comma(string): """Find the position of next comma in the string. If no ',' is found in the string, return the string length. All chars inside '()' and '[]' are treated as one element and thus ',' inside these brackets are ignored. """ assert (string.count('(') == string.count(')')) and ( string.count('[') == string.count(']')), \ f'Imbalanced brackets exist in {string}' end = len(string) for idx, char in enumerate(string): pre = string[:idx] # The string before this ',' is balanced if ((char == ',') and (pre.count('(') == pre.count(')')) and (pre.count('[') == pre.count(']'))): end = idx break return end # Strip ' and " characters and replace whitespace. val = val.strip('\'\"').replace(' ', '') is_tuple = False if val.startswith('(') and val.endswith(')'): is_tuple = True val = val[1:-1] elif val.startswith('[') and val.endswith(']'): val = val[1:-1] elif ',' not in val: # val is a single value return DictAction._parse_int_float_bool(val) values = [] while len(val) > 0: comma_idx = find_next_comma(val) element = DictAction._parse_iterable(val[:comma_idx]) values.append(element) val = val[comma_idx + 1:] if is_tuple: return tuple(values) return values
(val: str) -> Union[list, tuple, Any]
730,076
mmengine.fileio.file_client
FileClient
A general file client to access files in different backends. The client loads a file or text in a specified backend from its path and returns it as a binary or text file. There are two ways to choose a backend, the name of backend and the prefix of path. Although both of them can be used to choose a storage backend, ``backend`` has a higher priority that is if they are all set, the storage backend will be chosen by the backend argument. If they are all `None`, the disk backend will be chosen. Note that It can also register other backend accessor with a given name, prefixes, and backend class. In addition, We use the singleton pattern to avoid repeated object creation. If the arguments are the same, the same object will be returned. Warning: `FileClient` will be deprecated in future. Please use io functions in https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io Args: backend (str, optional): The storage backend type. Options are "disk", "memcached", "lmdb", "http" and "petrel". Defaults to None. prefix (str, optional): The prefix of the registered storage backend. Options are "s3", "http", "https". Defaults to None. Examples: >>> # only set backend >>> file_client = FileClient(backend='petrel') >>> # only set prefix >>> file_client = FileClient(prefix='s3') >>> # set both backend and prefix but use backend to choose client >>> file_client = FileClient(backend='petrel', prefix='s3') >>> # if the arguments are the same, the same object is returned >>> file_client1 = FileClient(backend='petrel') >>> file_client1 is file_client True Attributes: client (:obj:`BaseStorageBackend`): The backend object.
class FileClient: """A general file client to access files in different backends. The client loads a file or text in a specified backend from its path and returns it as a binary or text file. There are two ways to choose a backend, the name of backend and the prefix of path. Although both of them can be used to choose a storage backend, ``backend`` has a higher priority that is if they are all set, the storage backend will be chosen by the backend argument. If they are all `None`, the disk backend will be chosen. Note that It can also register other backend accessor with a given name, prefixes, and backend class. In addition, We use the singleton pattern to avoid repeated object creation. If the arguments are the same, the same object will be returned. Warning: `FileClient` will be deprecated in future. Please use io functions in https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io Args: backend (str, optional): The storage backend type. Options are "disk", "memcached", "lmdb", "http" and "petrel". Defaults to None. prefix (str, optional): The prefix of the registered storage backend. Options are "s3", "http", "https". Defaults to None. Examples: >>> # only set backend >>> file_client = FileClient(backend='petrel') >>> # only set prefix >>> file_client = FileClient(prefix='s3') >>> # set both backend and prefix but use backend to choose client >>> file_client = FileClient(backend='petrel', prefix='s3') >>> # if the arguments are the same, the same object is returned >>> file_client1 = FileClient(backend='petrel') >>> file_client1 is file_client True Attributes: client (:obj:`BaseStorageBackend`): The backend object. """ _backends = { 'disk': HardDiskBackend, 'memcached': MemcachedBackend, 'lmdb': LmdbBackend, 'petrel': PetrelBackend, 'http': HTTPBackend, } _prefix_to_backends: dict = { 's3': PetrelBackend, 'petrel': PetrelBackend, 'http': HTTPBackend, 'https': HTTPBackend, } _instances: dict = {} client: Any def __new__(cls, backend=None, prefix=None, **kwargs): print_log( '"FileClient" will be deprecated in future. Please use io ' 'functions in ' 'https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io', # noqa: E501 logger='current', level=logging.WARNING) if backend is None and prefix is None: backend = 'disk' if backend is not None and backend not in cls._backends: raise ValueError( f'Backend {backend} is not supported. Currently supported ones' f' are {list(cls._backends.keys())}') if prefix is not None and prefix not in cls._prefix_to_backends: raise ValueError( f'prefix {prefix} is not supported. Currently supported ones ' f'are {list(cls._prefix_to_backends.keys())}') # concatenate the arguments to a unique key for determining whether # objects with the same arguments were created arg_key = f'{backend}:{prefix}' for key, value in kwargs.items(): arg_key += f':{key}:{value}' # if a backend was overridden, it will create a new object if arg_key in cls._instances: _instance = cls._instances[arg_key] else: # create a new object and put it to _instance _instance = super().__new__(cls) if backend is not None: _instance.client = cls._backends[backend](**kwargs) else: _instance.client = cls._prefix_to_backends[prefix](**kwargs) cls._instances[arg_key] = _instance return _instance @property def name(self): return self.client.name @property def allow_symlink(self): return self.client.allow_symlink @staticmethod def parse_uri_prefix(uri: Union[str, Path]) -> Optional[str]: """Parse the prefix of a uri. Args: uri (str | Path): Uri to be parsed that contains the file prefix. Examples: >>> FileClient.parse_uri_prefix('s3://path/of/your/file') 's3' Returns: str | None: Return the prefix of uri if the uri contains '://' else ``None``. """ assert is_filepath(uri) uri = str(uri) if '://' not in uri: return None else: prefix, _ = uri.split('://') # In the case of PetrelBackend, the prefix may contains the cluster # name like clusterName:s3 if ':' in prefix: _, prefix = prefix.split(':') return prefix @classmethod def infer_client(cls, file_client_args: Optional[dict] = None, uri: Optional[Union[str, Path]] = None) -> 'FileClient': """Infer a suitable file client based on the URI and arguments. Args: file_client_args (dict, optional): Arguments to instantiate a FileClient. Defaults to None. uri (str | Path, optional): Uri to be parsed that contains the file prefix. Defaults to None. Examples: >>> uri = 's3://path/of/your/file' >>> file_client = FileClient.infer_client(uri=uri) >>> file_client_args = {'backend': 'petrel'} >>> file_client = FileClient.infer_client(file_client_args) Returns: FileClient: Instantiated FileClient object. """ assert file_client_args is not None or uri is not None if file_client_args is None: file_prefix = cls.parse_uri_prefix(uri) # type: ignore return cls(prefix=file_prefix) else: return cls(**file_client_args) @classmethod def _register_backend(cls, name, backend, force=False, prefixes=None): if not isinstance(name, str): raise TypeError('the backend name should be a string, ' f'but got {type(name)}') if not inspect.isclass(backend): raise TypeError( f'backend should be a class but got {type(backend)}') if not issubclass(backend, BaseStorageBackend): raise TypeError( f'backend {backend} is not a subclass of BaseStorageBackend') if not force and name in cls._backends: raise KeyError( f'{name} is already registered as a storage backend, ' 'add "force=True" if you want to override it') if name in cls._backends and force: for arg_key, instance in list(cls._instances.items()): if isinstance(instance.client, cls._backends[name]): cls._instances.pop(arg_key) cls._backends[name] = backend if prefixes is not None: if isinstance(prefixes, str): prefixes = [prefixes] else: assert isinstance(prefixes, (list, tuple)) for prefix in prefixes: if prefix not in cls._prefix_to_backends: cls._prefix_to_backends[prefix] = backend elif (prefix in cls._prefix_to_backends) and force: overridden_backend = cls._prefix_to_backends[prefix] for arg_key, instance in list(cls._instances.items()): if isinstance(instance.client, overridden_backend): cls._instances.pop(arg_key) else: raise KeyError( f'{prefix} is already registered as a storage backend,' ' add "force=True" if you want to override it') @classmethod def register_backend(cls, name, backend=None, force=False, prefixes=None): """Register a backend to FileClient. This method can be used as a normal class method or a decorator. .. code-block:: python class NewBackend(BaseStorageBackend): def get(self, filepath): return filepath def get_text(self, filepath): return filepath FileClient.register_backend('new', NewBackend) or .. code-block:: python @FileClient.register_backend('new') class NewBackend(BaseStorageBackend): def get(self, filepath): return filepath def get_text(self, filepath): return filepath Args: name (str): The name of the registered backend. backend (class, optional): The backend class to be registered, which must be a subclass of :class:`BaseStorageBackend`. When this method is used as a decorator, backend is None. Defaults to None. force (bool, optional): Whether to override the backend if the name has already been registered. Defaults to False. prefixes (str or list[str] or tuple[str], optional): The prefixes of the registered storage backend. Defaults to None. `New in version 1.3.15.` """ if backend is not None: cls._register_backend( name, backend, force=force, prefixes=prefixes) return def _register(backend_cls): cls._register_backend( name, backend_cls, force=force, prefixes=prefixes) return backend_cls return _register def get(self, filepath: Union[str, Path]) -> Union[bytes, memoryview]: """Read data from a given ``filepath`` with 'rb' mode. Note: There are two types of return values for ``get``, one is ``bytes`` and the other is ``memoryview``. The advantage of using memoryview is that you can avoid copying, and if you want to convert it to ``bytes``, you can use ``.tobytes()``. Args: filepath (str or Path): Path to read data. Returns: bytes | memoryview: Expected bytes object or a memory view of the bytes object. """ return self.client.get(filepath) def get_text(self, filepath: Union[str, Path], encoding='utf-8') -> str: """Read data from a given ``filepath`` with 'r' mode. Args: filepath (str or Path): Path to read data. encoding (str): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. Returns: str: Expected text reading from ``filepath``. """ return self.client.get_text(filepath, encoding) def put(self, obj: bytes, filepath: Union[str, Path]) -> None: """Write data to a given ``filepath`` with 'wb' mode. Note: ``put`` should create a directory if the directory of ``filepath`` does not exist. Args: obj (bytes): Data to be written. filepath (str or Path): Path to write data. """ self.client.put(obj, filepath) def put_text(self, obj: str, filepath: Union[str, Path]) -> None: """Write data to a given ``filepath`` with 'w' mode. Note: ``put_text`` should create a directory if the directory of ``filepath`` does not exist. Args: obj (str): Data to be written. filepath (str or Path): Path to write data. encoding (str, optional): The encoding format used to open the `filepath`. Defaults to 'utf-8'. """ self.client.put_text(obj, filepath) def remove(self, filepath: Union[str, Path]) -> None: """Remove a file. Args: filepath (str, Path): Path to be removed. """ self.client.remove(filepath) def exists(self, filepath: Union[str, Path]) -> bool: """Check whether a file path exists. Args: filepath (str or Path): Path to be checked whether exists. Returns: bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. """ return self.client.exists(filepath) def isdir(self, filepath: Union[str, Path]) -> bool: """Check whether a file path is a directory. Args: filepath (str or Path): Path to be checked whether it is a directory. Returns: bool: Return ``True`` if ``filepath`` points to a directory, ``False`` otherwise. """ return self.client.isdir(filepath) def isfile(self, filepath: Union[str, Path]) -> bool: """Check whether a file path is a file. Args: filepath (str or Path): Path to be checked whether it is a file. Returns: bool: Return ``True`` if ``filepath`` points to a file, ``False`` otherwise. """ return self.client.isfile(filepath) def join_path(self, filepath: Union[str, Path], *filepaths: Union[str, Path]) -> str: r"""Concatenate all file paths. Join one or more filepath components intelligently. The return value is the concatenation of filepath and any members of \*filepaths. Args: filepath (str or Path): Path to be concatenated. Returns: str: The result of concatenation. """ return self.client.join_path(filepath, *filepaths) @contextmanager def get_local_path( self, filepath: Union[str, Path]) -> Generator[Union[str, Path], None, None]: """Download data from ``filepath`` and write the data to local path. ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It can be called with ``with`` statement, and when exists from the ``with`` statement, the temporary path will be released. Note: If the ``filepath`` is a local path, just return itself. .. warning:: ``get_local_path`` is an experimental interface that may change in the future. Args: filepath (str or Path): Path to be read data. Examples: >>> file_client = FileClient(prefix='s3') >>> with file_client.get_local_path('s3://bucket/abc.jpg') as path: ... # do something here Yields: Iterable[str]: Only yield one path. """ with self.client.get_local_path(str(filepath)) as local_path: yield local_path def list_dir_or_file(self, dir_path: Union[str, Path], list_dir: bool = True, list_file: bool = True, suffix: Optional[Union[str, Tuple[str]]] = None, recursive: bool = False) -> Iterator[str]: """Scan a directory to find the interested directories or files in arbitrary order. Note: :meth:`list_dir_or_file` returns the path relative to ``dir_path``. Args: dir_path (str | Path): Path of the directory. list_dir (bool): List the directories. Defaults to True. list_file (bool): List the path of files. Defaults to True. suffix (str or tuple[str], optional): File suffix that we are interested in. Defaults to None. recursive (bool): If set to True, recursively scan the directory. Defaults to False. Yields: Iterable[str]: A relative path to ``dir_path``. """ yield from self.client.list_dir_or_file(dir_path, list_dir, list_file, suffix, recursive)
(backend=None, prefix=None, **kwargs)
730,077
mmengine.fileio.file_client
__new__
null
def __new__(cls, backend=None, prefix=None, **kwargs): print_log( '"FileClient" will be deprecated in future. Please use io ' 'functions in ' 'https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io', # noqa: E501 logger='current', level=logging.WARNING) if backend is None and prefix is None: backend = 'disk' if backend is not None and backend not in cls._backends: raise ValueError( f'Backend {backend} is not supported. Currently supported ones' f' are {list(cls._backends.keys())}') if prefix is not None and prefix not in cls._prefix_to_backends: raise ValueError( f'prefix {prefix} is not supported. Currently supported ones ' f'are {list(cls._prefix_to_backends.keys())}') # concatenate the arguments to a unique key for determining whether # objects with the same arguments were created arg_key = f'{backend}:{prefix}' for key, value in kwargs.items(): arg_key += f':{key}:{value}' # if a backend was overridden, it will create a new object if arg_key in cls._instances: _instance = cls._instances[arg_key] else: # create a new object and put it to _instance _instance = super().__new__(cls) if backend is not None: _instance.client = cls._backends[backend](**kwargs) else: _instance.client = cls._prefix_to_backends[prefix](**kwargs) cls._instances[arg_key] = _instance return _instance
(cls, backend=None, prefix=None, **kwargs)
730,078
mmengine.fileio.file_client
exists
Check whether a file path exists. Args: filepath (str or Path): Path to be checked whether exists. Returns: bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
def exists(self, filepath: Union[str, Path]) -> bool: """Check whether a file path exists. Args: filepath (str or Path): Path to be checked whether exists. Returns: bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise. """ return self.client.exists(filepath)
(self, filepath: Union[str, pathlib.Path]) -> bool
730,079
mmengine.fileio.file_client
get
Read data from a given ``filepath`` with 'rb' mode. Note: There are two types of return values for ``get``, one is ``bytes`` and the other is ``memoryview``. The advantage of using memoryview is that you can avoid copying, and if you want to convert it to ``bytes``, you can use ``.tobytes()``. Args: filepath (str or Path): Path to read data. Returns: bytes | memoryview: Expected bytes object or a memory view of the bytes object.
def get(self, filepath: Union[str, Path]) -> Union[bytes, memoryview]: """Read data from a given ``filepath`` with 'rb' mode. Note: There are two types of return values for ``get``, one is ``bytes`` and the other is ``memoryview``. The advantage of using memoryview is that you can avoid copying, and if you want to convert it to ``bytes``, you can use ``.tobytes()``. Args: filepath (str or Path): Path to read data. Returns: bytes | memoryview: Expected bytes object or a memory view of the bytes object. """ return self.client.get(filepath)
(self, filepath: Union[str, pathlib.Path]) -> Union[bytes, memoryview]
730,080
mmengine.fileio.file_client
get_local_path
Download data from ``filepath`` and write the data to local path. ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It can be called with ``with`` statement, and when exists from the ``with`` statement, the temporary path will be released. Note: If the ``filepath`` is a local path, just return itself. .. warning:: ``get_local_path`` is an experimental interface that may change in the future. Args: filepath (str or Path): Path to be read data. Examples: >>> file_client = FileClient(prefix='s3') >>> with file_client.get_local_path('s3://bucket/abc.jpg') as path: ... # do something here Yields: Iterable[str]: Only yield one path.
@classmethod def register_backend(cls, name, backend=None, force=False, prefixes=None): """Register a backend to FileClient. This method can be used as a normal class method or a decorator. .. code-block:: python class NewBackend(BaseStorageBackend): def get(self, filepath): return filepath def get_text(self, filepath): return filepath FileClient.register_backend('new', NewBackend) or .. code-block:: python @FileClient.register_backend('new') class NewBackend(BaseStorageBackend): def get(self, filepath): return filepath def get_text(self, filepath): return filepath Args: name (str): The name of the registered backend. backend (class, optional): The backend class to be registered, which must be a subclass of :class:`BaseStorageBackend`. When this method is used as a decorator, backend is None. Defaults to None. force (bool, optional): Whether to override the backend if the name has already been registered. Defaults to False. prefixes (str or list[str] or tuple[str], optional): The prefixes of the registered storage backend. Defaults to None. `New in version 1.3.15.` """ if backend is not None: cls._register_backend( name, backend, force=force, prefixes=prefixes) return def _register(backend_cls): cls._register_backend( name, backend_cls, force=force, prefixes=prefixes) return backend_cls return _register
(self, filepath: Union[str, pathlib.Path]) -> Generator[Union[str, pathlib.Path], NoneType, NoneType]
730,081
mmengine.fileio.file_client
get_text
Read data from a given ``filepath`` with 'r' mode. Args: filepath (str or Path): Path to read data. encoding (str): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. Returns: str: Expected text reading from ``filepath``.
def get_text(self, filepath: Union[str, Path], encoding='utf-8') -> str: """Read data from a given ``filepath`` with 'r' mode. Args: filepath (str or Path): Path to read data. encoding (str): The encoding format used to open the ``filepath``. Defaults to 'utf-8'. Returns: str: Expected text reading from ``filepath``. """ return self.client.get_text(filepath, encoding)
(self, filepath: Union[str, pathlib.Path], encoding='utf-8') -> str
730,082
mmengine.fileio.file_client
isdir
Check whether a file path is a directory. Args: filepath (str or Path): Path to be checked whether it is a directory. Returns: bool: Return ``True`` if ``filepath`` points to a directory, ``False`` otherwise.
def isdir(self, filepath: Union[str, Path]) -> bool: """Check whether a file path is a directory. Args: filepath (str or Path): Path to be checked whether it is a directory. Returns: bool: Return ``True`` if ``filepath`` points to a directory, ``False`` otherwise. """ return self.client.isdir(filepath)
(self, filepath: Union[str, pathlib.Path]) -> bool
730,083
mmengine.fileio.file_client
isfile
Check whether a file path is a file. Args: filepath (str or Path): Path to be checked whether it is a file. Returns: bool: Return ``True`` if ``filepath`` points to a file, ``False`` otherwise.
def isfile(self, filepath: Union[str, Path]) -> bool: """Check whether a file path is a file. Args: filepath (str or Path): Path to be checked whether it is a file. Returns: bool: Return ``True`` if ``filepath`` points to a file, ``False`` otherwise. """ return self.client.isfile(filepath)
(self, filepath: Union[str, pathlib.Path]) -> bool