def add_argument ( self , * args : Any , ** kwargs : Any ) -> None :
- r """
- Add an argument to `ConfigParser`.
-
- Note that value defined in `Config` will override the default value defined in `add_argument`.
-
- Examples:
- >>> c = Config(a=0, c=1)
- >>> arg = c.add_argument("--a", type=int, default=1)
- >>> arg = c.add_argument("--b", type=int, default=2)
- >>> c.parse(['--c', '4']).dict()
- {'a': 1, 'c': 4, 'b': 2}
- """
-
- if not self . hasattr ( "parser" ):
- self . setattr ( "parser" , ConfigParser ())
- return self . getattr ( "parser" ) . add_argument ( * args , ** kwargs )
+ Python def add_argument ( self , * args : Any , ** kwargs : Any ) -> None :
+ r """
+ Add an argument to `ConfigParser`.
+
+ Note that value defined in `Config` will override the default value defined in `add_argument`.
+
+ Examples:
+ >>> c = Config(a=0, c=1)
+ >>> arg = c.add_argument("--a", type=int, default=1)
+ >>> arg = c.add_argument("--b", type=int, default=2)
+ >>> c.parse(['--c', '4']).dict()
+ {'a': 1, 'c': 4, 'b': 2}
+ """
+
+ if self . getattr ( "parser" ) is None :
+ self . setattr ( "parser" , ConfigParser ())
+ return self . getattr ( "parser" ) . add_argument ( * args , ** kwargs )
@@ -2616,101 +2511,101 @@
Source code in chanfig/config.py
- Python def boot ( self ) -> Self :
- r """
- Apply `post` recursively.
-
- Sub-config may have their own `post` method.
- `boot` is provided to apply `post` recursively.
-
- By default, `boot` is called after `Config` is parsed.
- If you don't need to parse command-line arguments, you should call `boot` manually.
-
- See Also:
- [`post`][chanfig.Config.post]
-
- Returns:
- self:
-
- Examples:
- >>> class DataConfig(Config):
- ... def post(self):
- ... if isinstance(self.path, str):
- ... self.path = Config(feature=self.path, label=self.path)
- ... return self
- >>> class BootConfig(Config):
- ... def __init__(self, *args, **kwargs):
- ... super().__init__(*args, **kwargs)
- ... self.dataset = DataConfig(path="path")
- ... def post(self):
- ... if isinstance(self.id, str):
- ... self.id += "_id"
- ... return self
- >>> c = BootConfig(id="boot")
- >>> c.boot()
- BootConfig(<class 'chanfig.config.Config'>,
- ('id'): 'boot_id'
- ('dataset'): DataConfig(<class 'chanfig.config.Config'>,
- ('path'): Config(<class 'chanfig.config.Config'>,
- ('feature'): 'path'
- ('label'): 'path'
- )
- )
- )
- """
-
- for value in self . values ():
- if isinstance ( value , Config ):
- value . boot ()
- self . post ()
- return self
+ Python def boot ( self ) -> Self :
+ r """
+ Apply `post` recursively.
+
+ Sub-config may have their own `post` method.
+ `boot` is provided to apply `post` recursively.
+
+ By default, `boot` is called after `Config` is parsed.
+ If you don't need to parse command-line arguments, you should call `boot` manually.
+
+ See Also:
+ [`post`][chanfig.Config.post]
+
+ Returns:
+ self:
+
+ Examples:
+ >>> class DataConfig(Config):
+ ... def post(self):
+ ... if isinstance(self.path, str):
+ ... self.path = Config(feature=self.path, label=self.path)
+ ... return self
+ >>> class BootConfig(Config):
+ ... def __init__(self, *args, **kwargs):
+ ... super().__init__(*args, **kwargs)
+ ... self.dataset = DataConfig(path="path")
+ ... def post(self):
+ ... if isinstance(self.id, str):
+ ... self.id += "_id"
+ ... return self
+ >>> c = BootConfig(id="boot")
+ >>> c.boot()
+ BootConfig(<class 'chanfig.config.Config'>,
+ ('id'): 'boot_id'
+ ('dataset'): DataConfig(<class 'chanfig.config.Config'>,
+ ('path'): Config(<class 'chanfig.config.Config'>,
+ ('feature'): 'path'
+ ('label'): 'path'
+ )
+ )
+ )
+ """
+
+ for value in self . values ():
+ if isinstance ( value , Config ):
+ value . boot ()
+ self . post ()
+ return self
@@ -2720,15 +2615,15 @@
-
- copy_class_attributes ( recursive = True )
+
+ defrost ( recursive = True )
-
+
-
Copy class attributes to instance.
+
Defrost Config
.
Parameters:
@@ -2758,345 +2653,158 @@
+
Alias :
+
-
Returns:
+
Examples:
+
Python Console Session >>> c = Config ( ** { 'i.d' : 1013 })
+>>> c . getattr ( 'frozen' )
+False
+>>> c . freeze () . dict ()
+{'i': {'d': 1013}}
+>>> c . getattr ( 'frozen' )
+True
+>>> c . defrost ( recursive = False ) . dict ()
+{'i': {'d': 1013}}
+>>> c . getattr ( 'frozen' )
+False
+>>> c . i . getattr ( 'frozen' )
+True
+>>> c . unlock () . dict () # alias
+{'i': {'d': 1013}}
+>>> c . i . getattr ( 'frozen' )
+False
+
+
+
+ Source code in chanfig/config.py
+ Python def defrost ( self , recursive : bool = True ) -> Self :
+ r """
+ Defrost `Config`.
+
+ Args:
+ recursive:
+
+ **Alias**:
+
+ + `unlock`
+
+ Examples:
+ >>> c = Config(**{'i.d': 1013})
+ >>> c.getattr('frozen')
+ False
+ >>> c.freeze().dict()
+ {'i': {'d': 1013}}
+ >>> c.getattr('frozen')
+ True
+ >>> c.defrost(recursive=False).dict()
+ {'i': {'d': 1013}}
+ >>> c.getattr('frozen')
+ False
+ >>> c.i.getattr('frozen')
+ True
+ >>> c.unlock().dict() # alias
+ {'i': {'d': 1013}}
+ >>> c.i.getattr('frozen')
+ False
+ """
+
+ @wraps ( self . defrost )
+ def defrost ( config : Config ) -> None :
+ if isinstance ( config , Config ):
+ config . setattr ( "frozen" , False )
+
+ if recursive :
+ self . apply_ ( defrost )
+ else :
+ defrost ( self )
+ return self
+
+
+
+
+
+
+
+
+
+
+ delete ( name )
+
+
+
+
+
+
+
Delete value from Config
.
+
+
+
Parameters:
-Name Type
+ Name
+ Type
Description
+ Default
-self
- Self
+ name
+
+ Any
-
-
-
-
-
-
-
Examples:
-
Python Console Session >>> class Ancestor ( Config ):
-... a = 1
->>> class Parent ( Ancestor ):
-... b = 2
->>> class Child ( Parent ):
-... c = 3
->>> c = Child ()
->>> c
-Child(<class 'chanfig.config.Config'>, )
->>> c . copy_class_attributes ( recursive = False )
-Child(<class 'chanfig.config.Config'>,('c'): 3)
->>> c . copy_class_attributes ()
-Child(<class 'chanfig.config.Config'>,
- ('a'): 1,
- ('b'): 2,
- ('c'): 3
-)
-
-
-
- Source code in chanfig/config.py
- Python def copy_class_attributes ( self , recursive : bool = True ) -> Self :
- r """
- Copy class attributes to instance.
-
- Args:
- recursive:
-
- Returns:
- self:
-
- Examples:
- >>> class Ancestor(Config):
- ... a = 1
- >>> class Parent(Ancestor):
- ... b = 2
- >>> class Child(Parent):
- ... c = 3
- >>> c = Child()
- >>> c
- Child(<class 'chanfig.config.Config'>, )
- >>> c.copy_class_attributes(recursive=False)
- Child(<class 'chanfig.config.Config'>,('c'): 3)
- >>> c.copy_class_attributes() # doctest: +SKIP
- Child(<class 'chanfig.config.Config'>,
- ('a'): 1,
- ('b'): 2,
- ('c'): 3
- )
- """
-
- def copy_cls_attributes ( cls : type ) -> Mapping :
- return {
- k : v
- for k , v in cls . __dict__ . items ()
- if k not in self
- and not k . startswith ( "__" )
- and ( not ( isinstance ( v , ( property , staticmethod , classmethod )) or callable ( v )))
- }
-
- if recursive :
- for cls in self . __class__ . __mro__ :
- if cls . __module__ . startswith ( "chanfig" ):
- break
- self . merge ( copy_cls_attributes ( cls ), overwrite = False )
- else :
- self . merge ( copy_cls_attributes ( self . __class__ ), overwrite = False )
- return self
-
-
-
-
-
-
-
-
-
-
- defrost ( recursive = True )
-
-
-
-
-
-
-
Defrost Config
.
-
-
-
Parameters:
-
-
-
- Name
- Type
- Description
- Default
-
-
-
-
- recursive
-
- bool
-
-
-
-
-
-
-
- True
-
-
-
-
-
Alias :
-
-
-
-
Examples:
-
Python Console Session >>> c = Config ( ** { 'i.d' : 1013 })
->>> c . getattr ( 'frozen' )
-False
->>> c . freeze () . dict ()
-{'i': {'d': 1013}}
->>> c . getattr ( 'frozen' )
-True
->>> c . defrost ( recursive = False ) . dict ()
-{'i': {'d': 1013}}
->>> c . getattr ( 'frozen' )
-False
->>> c . i . getattr ( 'frozen' )
-True
->>> c . unlock () . dict () # alias
-{'i': {'d': 1013}}
->>> c . i . getattr ( 'frozen' )
-False
-
-
-
- Source code in chanfig/config.py
- Python def defrost ( self , recursive : bool = True ) -> Self :
- r """
- Defrost `Config`.
-
- Args:
- recursive:
-
- **Alias**:
-
- + `unlock`
-
- Examples:
- >>> c = Config(**{'i.d': 1013})
- >>> c.getattr('frozen')
- False
- >>> c.freeze().dict()
- {'i': {'d': 1013}}
- >>> c.getattr('frozen')
- True
- >>> c.defrost(recursive=False).dict()
- {'i': {'d': 1013}}
- >>> c.getattr('frozen')
- False
- >>> c.i.getattr('frozen')
- True
- >>> c.unlock().dict() # alias
- {'i': {'d': 1013}}
- >>> c.i.getattr('frozen')
- False
- """
-
- @wraps ( self . defrost )
- def defrost ( config : Config ) -> None :
- if isinstance ( config , Config ):
- config . setattr ( "frozen" , False )
-
- if recursive :
- self . apply_ ( defrost )
- else :
- defrost ( self )
- return self
-
-
-
-
-
-
-
-
-
-
- delete ( name )
-
-
-
-
-
-
-
Delete value from Config
.
-
-
-
Parameters:
-
-
-
- Name
- Type
- Description
- Default
-
-
-
-
- name
-
- Any
-
-
-
-
-
-
-
- required
+
+
+ required
@@ -3126,65 +2834,65 @@
Source code in chanfig/config.py
- Python @frozen_check
-def delete ( self , name : Any ) -> None :
- r """
- Delete value from `Config`.
-
- Args:
- name:
-
- Examples:
- >>> d = Config(**{"i.d": 1013, "f.n": "chang"})
- >>> d.i.d
- 1013
- >>> d.f.n
- 'chang'
- >>> d.delete('i.d')
- >>> "i.d" in d
- False
- >>> d.i.d
- Config(<class 'chanfig.config.Config'>, )
- >>> "i.d" in d
- True
- >>> del d.f.n
- >>> d.f.n
- Config(<class 'chanfig.config.Config'>, )
- >>> del d.c
- Traceback (most recent call last):
- AttributeError: 'Config' object has no attribute 'c'
- """
-
- super () . delete ( name )
+ Python @frozen_check
+def delete ( self , name : Any ) -> None :
+ r """
+ Delete value from `Config`.
+
+ Args:
+ name:
+
+ Examples:
+ >>> d = Config(**{"i.d": 1013, "f.n": "chang"})
+ >>> d.i.d
+ 1013
+ >>> d.f.n
+ 'chang'
+ >>> d.delete('i.d')
+ >>> "i.d" in d
+ False
+ >>> d.i.d
+ Config(<class 'chanfig.config.Config'>, )
+ >>> "i.d" in d
+ True
+ >>> del d.f.n
+ >>> d.f.n
+ Config(<class 'chanfig.config.Config'>, )
+ >>> del d.c
+ Traceback (most recent call last):
+ AttributeError: 'Config' object has no attribute 'c'
+ """
+
+ super () . delete ( name )
@@ -3256,79 +2964,79 @@
Source code in chanfig/config.py
- Python def freeze ( self , recursive : bool = True ) -> Self :
- r """
- Freeze `Config`.
-
- Args:
- recursive:
-
- **Alias**:
-
- + `lock`
-
- Examples:
- >>> c = Config(**{'i.d': 1013})
- >>> c.getattr('frozen')
- False
- >>> c.freeze(recursive=False).dict()
- {'i': {'d': 1013}}
- >>> c.getattr('frozen')
- True
- >>> c.i.getattr('frozen')
- False
- >>> c.lock().dict() # alias
- {'i': {'d': 1013}}
- >>> c.i.getattr('frozen')
- True
- """
-
- @wraps ( self . freeze )
- def freeze ( config : Config ) -> None :
- if isinstance ( config , Config ):
- config . setattr ( "frozen" , True )
-
- if recursive :
- self . apply_ ( freeze )
- else :
- freeze ( self )
- return self
+ Python def freeze ( self , recursive : bool = True ) -> Self :
+ r """
+ Freeze `Config`.
+
+ Args:
+ recursive:
+
+ **Alias**:
+
+ + `lock`
+
+ Examples:
+ >>> c = Config(**{'i.d': 1013})
+ >>> c.getattr('frozen')
+ False
+ >>> c.freeze(recursive=False).dict()
+ {'i': {'d': 1013}}
+ >>> c.getattr('frozen')
+ True
+ >>> c.i.getattr('frozen')
+ False
+ >>> c.lock().dict() # alias
+ {'i': {'d': 1013}}
+ >>> c.i.getattr('frozen')
+ True
+ """
+
+ @wraps ( self . freeze )
+ def freeze ( config : Config ) -> None :
+ if isinstance ( config , Config ):
+ config . setattr ( "frozen" , True )
+
+ if recursive :
+ self . apply_ ( freeze )
+ else :
+ freeze ( self )
+ return self
@@ -3466,108 +3174,108 @@
Traceback (most recent call last):
KeyError : 'f.n'
-
-
- Source code in chanfig/config.py
- Python def get ( self , name : Any , default : Any = None , fallback : bool | None = None ) -> Any :
- r """
- Get value from `Config`.
-
- Note that `default` has higher priority than `default_factory`.
-
- Args:
- name:
- default:
-
- Returns:
- value:
- If `Config` does not contain `name`, return `default`.
- If `default` is not specified, return `default_factory()`.
-
- Raises:
- KeyError: If `Config` does not contain `name` and `default`/`default_factory` is not specified.
-
- Examples:
- >>> d = Config(**{"i.d": 1013})
- >>> d.get('i.d')
- 1013
- >>> d['i.d']
- 1013
- >>> d.i.d
- 1013
- >>> d.get('f', 2)
- 2
- >>> d.f
- Config(<class 'chanfig.config.Config'>, )
- >>> del d.f
- >>> d.freeze()
- Config(<class 'chanfig.config.Config'>,
- ('i'): Config(<class 'chanfig.config.Config'>,
- ('d'): 1013
- )
- )
- >>> d.f
- Traceback (most recent call last):
- AttributeError: 'Config' object has no attribute 'f'
- >>> d["f.n"]
- Traceback (most recent call last):
- KeyError: 'f.n'
- """
-
- if not self . hasattr ( "default_factory" ): # did not call super().__init__() in sub-class
- self . setattr ( "default_factory" , Config )
- if name in self or not self . getattr ( "frozen" , False ):
- return super () . get ( name , default , fallback )
- raise KeyError ( name )
+
+
+ Source code in chanfig/config.py
+ Python def get ( self , name : Any , default : Any = None , fallback : bool | None = None ) -> Any :
+ r """
+ Get value from `Config`.
+
+ Note that `default` has higher priority than `default_factory`.
+
+ Args:
+ name:
+ default:
+
+ Returns:
+ value:
+ If `Config` does not contain `name`, return `default`.
+ If `default` is not specified, return `default_factory()`.
+
+ Raises:
+ KeyError: If `Config` does not contain `name` and `default`/`default_factory` is not specified.
+
+ Examples:
+ >>> d = Config(**{"i.d": 1013})
+ >>> d.get('i.d')
+ 1013
+ >>> d['i.d']
+ 1013
+ >>> d.i.d
+ 1013
+ >>> d.get('f', 2)
+ 2
+ >>> d.f
+ Config(<class 'chanfig.config.Config'>, )
+ >>> del d.f
+ >>> d.freeze()
+ Config(<class 'chanfig.config.Config'>,
+ ('i'): Config(<class 'chanfig.config.Config'>,
+ ('d'): 1013
+ )
+ )
+ >>> d.f
+ Traceback (most recent call last):
+ AttributeError: 'Config' object has no attribute 'f'
+ >>> d["f.n"]
+ Traceback (most recent call last):
+ KeyError: 'f.n'
+ """
+
+ if not self . hasattr ( "default_factory" ): # did not call super().__init__() in sub-class
+ self . setattr ( "default_factory" , Config )
+ if name in self or not self . getattr ( "frozen" , False ):
+ return super () . get ( name , default , fallback )
+ raise KeyError ( name )
@@ -3589,15 +3297,15 @@
Source code in chanfig/config.py
- Python def lock ( self , recursive : bool = True ) -> Self :
- r """
- Alias of [`freeze`][chanfig.Config.freeze].
- """
- return self . freeze ( recursive = recursive )
+ Python def lock ( self , recursive : bool = True ) -> Self :
+ r """
+ Alias of [`freeze`][chanfig.Config.freeze].
+ """
+ return self . freeze ( recursive = recursive )
@@ -3631,51 +3339,51 @@
Source code in chanfig/config.py
- Python @contextmanager
-def locked ( self ):
- """
- Context manager which temporarily locks `Config`.
-
- Examples:
- >>> c = Config()
- >>> with c.locked():
- ... c['i.d'] = 1013
- Traceback (most recent call last):
- ValueError: Attempting to alter a frozen config. Run config.defrost() to defrost first.
- >>> c.i.d = 1013
- >>> c.dict()
- {'i': {'d': 1013}}
- """
-
- was_frozen = self . getattr ( "frozen" , False )
- try :
- self . freeze ()
- yield self
- finally :
- if not was_frozen :
- self . defrost ()
+ Python @contextmanager
+def locked ( self ):
+ """
+ Context manager which temporarily locks `Config`.
+
+ Examples:
+ >>> c = Config()
+ >>> with c.locked():
+ ... c['i.d'] = 1013
+ Traceback (most recent call last):
+ ValueError: Attempting to alter a frozen config. Run config.defrost() to defrost first.
+ >>> c.i.d = 1013
+ >>> c.dict()
+ {'i': {'d': 1013}}
+ """
+
+ was_frozen = self . getattr ( "frozen" , False )
+ try :
+ self . freeze ()
+ yield self
+ finally :
+ if not was_frozen :
+ self . defrost ()
@@ -3788,89 +3496,89 @@
Source code in chanfig/config.py
- Python def parse (
- self ,
- args : Iterable [ str ] | None = None ,
- default_config : str | None = None ,
- no_default_config_action : str = "raise" ,
- boot : bool = True ,
-) -> Self :
- r """
-
- Parse command-line arguments with `ConfigParser`.
-
- `parse` will try to parse all command-line arguments,
- you don't need to pre-define them but typos may cause trouble.
-
- By default, this method internally calls `Config.boot()`.
- To disable this behaviour, set `boot` to `False`.
-
- Args:
- args (Iterable[str] | None, optional): Command-line arguments. Defaults to `None`.
- default_config (str | None, optional): Path to default config file. Defaults to `None`.
- no_default_config_action (str, optional): Action when `default_config` is not found.
- Can be one of `["raise", "warn", "ignore"]`. Defaults to `"raise"`.
- boot (bool, optional): If `True`, call `Config.boot()` after parsing. Defaults to `True`.
-
- See Also:
- [`chanfig.ConfigParser.parse`][chanfig.ConfigParser.parse]: Implementation of `parse`.
- [`parse_config`][chanfig.Config.parse_config]: Only parse valid config arguments.
-
- Examples:
- >>> c = Config(a=0)
- >>> c.dict()
- {'a': 0}
- >>> c.parse(['--a', '1', '--b', '2', '--c', '3']).dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- if not self . hasattr ( "parser" ):
- self . setattr ( "parser" , ConfigParser ())
- self . getattr ( "parser" ) . parse ( args , self , default_config , no_default_config_action )
- if boot :
- self . boot ()
- return self
+ Python def parse (
+ self ,
+ args : Iterable [ str ] | None = None ,
+ default_config : str | None = None ,
+ no_default_config_action : str = "raise" ,
+ boot : bool = True ,
+) -> Self :
+ r """
+
+ Parse command-line arguments with `ConfigParser`.
+
+ `parse` will try to parse all command-line arguments,
+ you don't need to pre-define them but typos may cause trouble.
+
+ By default, this method internally calls `Config.boot()`.
+ To disable this behaviour, set `boot` to `False`.
+
+ Args:
+ args (Iterable[str] | None, optional): Command-line arguments. Defaults to `None`.
+ default_config (str | None, optional): Path to default config file. Defaults to `None`.
+ no_default_config_action (str, optional): Action when `default_config` is not found.
+ Can be one of `["raise", "warn", "ignore"]`. Defaults to `"raise"`.
+ boot (bool, optional): If `True`, call `Config.boot()` after parsing. Defaults to `True`.
+
+ See Also:
+ [`chanfig.ConfigParser.parse`][chanfig.ConfigParser.parse]: Implementation of `parse`.
+ [`parse_config`][chanfig.Config.parse_config]: Only parse valid config arguments.
+
+ Examples:
+ >>> c = Config(a=0)
+ >>> c.dict()
+ {'a': 0}
+ >>> c.parse(['--a', '1', '--b', '2', '--c', '3']).dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ if self . getattr ( "parser" ) is None :
+ self . setattr ( "parser" , ConfigParser ())
+ self . getattr ( "parser" ) . parse ( args , self , default_config , no_default_config_action )
+ if boot :
+ self . boot ()
+ return self
@@ -3982,87 +3690,87 @@
Source code in chanfig/config.py
- Python def parse_config (
- self ,
- args : Iterable [ str ] | None = None ,
- default_config : str | None = None ,
- no_default_config_action : str = "raise" ,
- boot : bool = True ,
-) -> Self :
- r """
-
- Parse command-line arguments with `ConfigParser`.
-
- `parse_config` only parse command-line arguments that is in defined in `Config`.
-
- By default, this method internally calls `Config.boot()`.
- To disable this behaviour, set `boot` to `False`.
-
- Args:
- args (Iterable[str] | None, optional): Command-line arguments. Defaults to `None`.
- default_config (str | None, optional): Path to default config file. Defaults to `None`.
- no_default_config_action (str, optional): Action when `default_config` is not found.
- Can be one of `["raise", "warn", "ignore"]`. Defaults to `"raise"`.
- boot (bool, optional): If `True`, call `Config.boot()` after parsing. Defaults to `True`.
-
- See Also:
- [`chanfig.ConfigParser.parse_config`][chanfig.ConfigParser.parse_config]: Implementation of `parse_config`.
- [`parse`][chanfig.Config.parse]: Parse all command-line arguments.
-
- Examples:
- >>> c = Config(a=0, b=0, c=0)
- >>> c.dict()
- {'a': 0, 'b': 0, 'c': 0}
- >>> c.parse_config(['--a', '1', '--b', '2', '--c', '3']).dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- if not self . hasattr ( "parser" ):
- self . setattr ( "parser" , ConfigParser ())
- self . getattr ( "parser" ) . parse_config ( args , self , default_config , no_default_config_action )
- if boot :
- self . boot ()
- return self
+ Python def parse_config (
+ self ,
+ args : Iterable [ str ] | None = None ,
+ default_config : str | None = None ,
+ no_default_config_action : str = "raise" ,
+ boot : bool = True ,
+) -> Self :
+ r """
+
+ Parse command-line arguments with `ConfigParser`.
+
+ `parse_config` only parse command-line arguments that is in defined in `Config`.
+
+ By default, this method internally calls `Config.boot()`.
+ To disable this behaviour, set `boot` to `False`.
+
+ Args:
+ args (Iterable[str] | None, optional): Command-line arguments. Defaults to `None`.
+ default_config (str | None, optional): Path to default config file. Defaults to `None`.
+ no_default_config_action (str, optional): Action when `default_config` is not found.
+ Can be one of `["raise", "warn", "ignore"]`. Defaults to `"raise"`.
+ boot (bool, optional): If `True`, call `Config.boot()` after parsing. Defaults to `True`.
+
+ See Also:
+ [`chanfig.ConfigParser.parse_config`][chanfig.ConfigParser.parse_config]: Implementation of `parse_config`.
+ [`parse`][chanfig.Config.parse]: Parse all command-line arguments.
+
+ Examples:
+ >>> c = Config(a=0, b=0, c=0)
+ >>> c.dict()
+ {'a': 0, 'b': 0, 'c': 0}
+ >>> c.parse_config(['--a', '1', '--b', '2', '--c', '3']).dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ if self . getattr ( "parser" ) is None :
+ self . setattr ( "parser" , ConfigParser ())
+ self . getattr ( "parser" ) . parse_config ( args , self , default_config , no_default_config_action )
+ if boot :
+ self . boot ()
+ return self
@@ -4170,69 +3878,69 @@
Source code in chanfig/config.py
- Python @frozen_check
-def pop ( self , name : Any , default : Any = Null ) -> Any :
- r """
- Pop value from `Config`.
-
- Args:
- name:
- default:
-
- Returns:
- value: If `Config` does not contain `name`, return `default`.
-
- Examples:
- >>> c = Config()
- >>> c['i.d'] = 1013
- >>> c.pop('i.d')
- 1013
- >>> c.pop('i.d', True)
- True
- >>> c.freeze().dict()
- {'i': {}}
- >>> c['i.d'] = 1013
- Traceback (most recent call last):
- ValueError: Attempting to alter a frozen config. Run config.defrost() to defrost first.
- >>> c.defrost().dict()
- {'i': {}}
- >>> c['i.d'] = 1013
- >>> c.pop('i.d')
- 1013
- """
-
- return super () . pop ( name , default )
+ Python @frozen_check
+def pop ( self , name : Any , default : Any = Null ) -> Any :
+ r """
+ Pop value from `Config`.
+
+ Args:
+ name:
+ default:
+
+ Returns:
+ value: If `Config` does not contain `name`, return `default`.
+
+ Examples:
+ >>> c = Config()
+ >>> c['i.d'] = 1013
+ >>> c.pop('i.d')
+ 1013
+ >>> c.pop('i.d', True)
+ True
+ >>> c.freeze().dict()
+ {'i': {}}
+ >>> c['i.d'] = 1013
+ Traceback (most recent call last):
+ ValueError: Attempting to alter a frozen config. Run config.defrost() to defrost first.
+ >>> c.defrost().dict()
+ {'i': {}}
+ >>> c['i.d'] = 1013
+ >>> c.pop('i.d')
+ 1013
+ """
+
+ return super () . pop ( name , default )
@@ -4314,101 +4022,101 @@
Source code in chanfig/config.py
- Python def post ( self ) -> Self | None :
- r """
- Post process of `Config`.
-
- Some `Config` may need to do some post process after `Config` is initialised.
- `post` is provided for this lazy-initialisation purpose.
-
- By default, `post` calls `interpolate` to perform variable interpolation.
-
- Note that you should always call `boot` to apply `post` rather than calling `post` directly,
- as `boot` recursively call `post` on sub-configs.
-
- See Also:
- [`boot`][chanfig.Config.boot]
-
- Returns:
- self:
-
- Examples:
- >>> c = Config()
- >>> c.dne
- Config(<class 'chanfig.config.Config'>, )
- >>> c.post()
- Config(
- ('dne'): Config()
- )
- >>> c.dne2
- Traceback (most recent call last):
- AttributeError: 'Config' object has no attribute 'dne2'
- >>> class PostConfig(Config):
- ... def post(self):
- ... if isinstance(self.data, str):
- ... self.data = Config(feature=self.data, label=self.data)
- ... return self
- >>> c = PostConfig(data="path")
- >>> c.post()
- PostConfig(<class 'chanfig.config.Config'>,
- ('data'): Config(<class 'chanfig.config.Config'>,
- ('feature'): 'path'
- ('label'): 'path'
- )
- )
- """
-
- self . interpolate ()
- self . validate ()
- self . apply_ ( lambda c : c . setattr ( "default_factory" , None ) if isinstance ( c , Config ) else None )
- return self
+ Python def post ( self ) -> Self | None :
+ r """
+ Post process of `Config`.
+
+ Some `Config` may need to do some post process after `Config` is initialised.
+ `post` is provided for this lazy-initialisation purpose.
+
+ By default, `post` calls `interpolate` to perform variable interpolation.
+
+ Note that you should always call `boot` to apply `post` rather than calling `post` directly,
+ as `boot` recursively call `post` on sub-configs.
+
+ See Also:
+ [`boot`][chanfig.Config.boot]
+
+ Returns:
+ self:
+
+ Examples:
+ >>> c = Config()
+ >>> c.dne
+ Config(<class 'chanfig.config.Config'>, )
+ >>> c.post()
+ Config(
+ ('dne'): Config()
+ )
+ >>> c.dne2
+ Traceback (most recent call last):
+ AttributeError: 'Config' object has no attribute 'dne2'
+ >>> class PostConfig(Config):
+ ... def post(self):
+ ... if isinstance(self.data, str):
+ ... self.data = Config(feature=self.data, label=self.data)
+ ... return self
+ >>> c = PostConfig(data="path")
+ >>> c.post()
+ PostConfig(<class 'chanfig.config.Config'>,
+ ('data'): Config(<class 'chanfig.config.Config'>,
+ ('feature'): 'path'
+ ('label'): 'path'
+ )
+ )
+ """
+
+ self . interpolate ()
+ self . validate ()
+ self . apply_ ( lambda c : c . setattr ( "default_factory" , None ) if isinstance ( c , Config ) else None )
+ return self
@@ -4529,79 +4237,79 @@
Source code in chanfig/config.py
- Python @frozen_check
-def set (
- self ,
- name : Any ,
- value : Any ,
- convert_mapping : bool | None = None ,
-) -> None :
- r """
- Set value of `Config`.
-
- Args:
- name:
- value:
- convert_mapping: Whether to convert `Mapping` to `NestedDict`.
- Defaults to self.convert_mapping.
-
- Raises:
- ValueError: If `Config` is frozen.
-
- Examples:
- >>> c = Config()
- >>> c['i.d'] = 1013
- >>> c.i.d
- 1013
- >>> c.freeze().dict()
- {'i': {'d': 1013}}
- >>> c['i.d'] = 1013
- Traceback (most recent call last):
- ValueError: Attempting to alter a frozen config. Run config.defrost() to defrost first.
- >>> c.defrost().dict()
- {'i': {'d': 1013}}
- >>> c['i.d'] = 1013
- >>> c.i.d
- 1013
- """
-
- return super () . set ( name , value , convert_mapping )
+ Python @frozen_check
+def set (
+ self ,
+ name : Any ,
+ value : Any ,
+ convert_mapping : bool | None = None ,
+) -> None :
+ r """
+ Set value of `Config`.
+
+ Args:
+ name:
+ value:
+ convert_mapping: Whether to convert `Mapping` to `NestedDict`.
+ Defaults to self.convert_mapping.
+
+ Raises:
+ ValueError: If `Config` is frozen.
+
+ Examples:
+ >>> c = Config()
+ >>> c['i.d'] = 1013
+ >>> c.i.d
+ 1013
+ >>> c.freeze().dict()
+ {'i': {'d': 1013}}
+ >>> c['i.d'] = 1013
+ Traceback (most recent call last):
+ ValueError: Attempting to alter a frozen config. Run config.defrost() to defrost first.
+ >>> c.defrost().dict()
+ {'i': {'d': 1013}}
+ >>> c['i.d'] = 1013
+ >>> c.i.d
+ 1013
+ """
+
+ return super () . set ( name , value , convert_mapping )
@@ -4623,15 +4331,15 @@
Source code in chanfig/config.py
- Python def unlock ( self , recursive : bool = True ) -> Self :
- r """
- Alias of [`defrost`][chanfig.Config.defrost].
- """
- return self . defrost ( recursive = recursive )
+ Python def unlock ( self , recursive : bool = True ) -> Self :
+ r """
+ Alias of [`defrost`][chanfig.Config.defrost].
+ """
+ return self . defrost ( recursive = recursive )
@@ -4664,49 +4372,49 @@
Source code in chanfig/config.py
- Python @contextmanager
-def unlocked ( self ):
- """
- Context manager which temporarily unlocks `Config`.
-
- Examples:
- >>> c = Config()
- >>> c.freeze().dict()
- {}
- >>> with c.unlocked():
- ... c['i.d'] = 1013
- >>> c.defrost().dict()
- {'i': {'d': 1013}}
- """
-
- was_frozen = self . getattr ( "frozen" , False )
- try :
- self . defrost ()
- yield self
- finally :
- if was_frozen :
- self . freeze ()
+ Python @contextmanager
+def unlocked ( self ):
+ """
+ Context manager which temporarily unlocks `Config`.
+
+ Examples:
+ >>> c = Config()
+ >>> c.freeze().dict()
+ {}
+ >>> with c.unlocked():
+ ... c['i.d'] = 1013
+ >>> c.defrost().dict()
+ {'i': {'d': 1013}}
+ """
+
+ was_frozen = self . getattr ( "frozen" , False )
+ try :
+ self . defrost ()
+ yield self
+ finally :
+ if was_frozen :
+ self . freeze ()
diff --git a/configclass/index.html b/configclass/index.html
index 55d3bcd2..3002ba86 100644
--- a/configclass/index.html
+++ b/configclass/index.html
@@ -1003,7 +1003,7 @@ configclass
@@ -1044,20 +1044,6 @@
None
-
- recursive
-
- bool
-
-
-
-
If True, recursively copy class attributes. Only applicable if used with parentheses.
-
-
-
- False
-
-
@@ -1101,8 +1087,7 @@
Source code in chanfig/configclasses.py
- Python 24
-25
+ Python def configclass ( cls = None , recursive : bool = False ):
- """
- Construct a Config in [`dataclass`][dataclasses.dataclass] style.
-
- This decorator creates a Config instance with the provided class attributes.
-
- See Also:
- [`dataclass`][dataclasses.dataclass]
-
- Args:
- cls (Type[Any]): The class to be enhanced, provided directly if no parentheses are used.
- recursive (bool): If True, recursively copy class attributes. Only applicable if used with parentheses.
+71
def configclass ( cls = None ):
+ """
+ Construct a Config in [`dataclass`][dataclasses.dataclass] style.
+
+ This decorator creates a Config instance with the provided class attributes.
+
+ See Also:
+ [`dataclass`][dataclasses.dataclass]
+
+ Args:
+ cls (Type[Any]): The class to be enhanced, provided directly if no parentheses are used.
Returns:
A modified class with Config functionalities or a decorator with bound parameters.
@@ -1183,27 +1163,23 @@
)
"""
- def decorator ( cls : Type [ Any ]):
- if not issubclass ( cls , Config ):
- config_cls = type ( cls . __name__ , ( Config , cls ), dict ( cls . __dict__ ))
- cls = config_cls
-
- cls_init = cls . __init__
+ warn (
+ "This decorator is deprecated and may be removed in the future release. "
+ "All chanfig classes will copy variable identified in `__annotations__` by default."
+ "This decorator is equivalent to inheriting from `Config`." ,
+ PendingDeprecationWarning ,
+ )
- @wraps ( cls_init )
- def init ( self , * args , ** kwargs ):
- cls_init ( self )
- self . copy_class_attributes ( recursive = recursive )
- self . merge ( * args , ** kwargs )
-
- setattr ( cls , "__init__" , init ) # noqa: B010
-
- return cls
-
- if cls is None :
- return decorator
- else :
- return decorator ( cls )
+ def decorator ( cls : Type [ Any ]):
+ if not issubclass ( cls , Config ):
+ config_cls = type ( cls . __name__ , ( Config , cls ), dict ( cls . __dict__ ))
+ cls = config_cls
+
+ return cls
+
+ if cls is None :
+ return decorator
+ return decorator ( cls )
diff --git a/default_dict/index.html b/default_dict/index.html
index 40d8879a..0a6e1481 100644
--- a/default_dict/index.html
+++ b/default_dict/index.html
@@ -1161,7 +1161,9 @@ class DefaultDict ( FlatDict ):
r """
`DefaultDict` inherits from `FlatDict` and incorporates support of `default_factory`
in the same manner as `collections.defaultdict`.
@@ -1219,44 +1221,46 @@ DefaultDict return default
def __repr__ ( self ) -> str :
- if self . default_factory is None :
- return super () . __repr__ ()
- super_repr = super () . __repr__ ()[ len ( self . __class__ . __name__ ) :] # noqa: E203
- if len ( super_repr ) == 2 :
- return f " { self . __class__ . __name__ } ( { self . default_factory } , )"
- return f " { self . __class__ . __name__ } ( { self . default_factory } ," + super_repr [ 1 :]
-
- def add ( self , name : Any ):
- r """
- Add a new default factory to the dictionary.
-
- Args:
- name:
-
- Raises:
- ValueError: If `default_factory` is None.
-
- Examples:
- >>> d = DefaultDict(default_factory=DefaultDict)
- >>> d.add('d')
- DefaultDict()
- >>> d.get('d')
- DefaultDict()
- >>> d['n'] = 'chang'
- >>> d.n
- 'chang'
- >>> d.n = 'liu'
- >>> d['n']
- 'liu'
- >>> d = DefaultDict()
- >>> d.add('a')
- Traceback (most recent call last):
- ValueError: Cannot add to a DefaultDict with no default_factory
- """
- if self . default_factory is None :
- raise ValueError ( "Cannot add to a DefaultDict with no default_factory" )
- self . set ( name , self . default_factory ()) # pylint: disable=E1102
- return self . get ( name )
+ default_factory = self . getattr ( "default_factory" , None )
+ if default_factory is None :
+ return super () . __repr__ ()
+ super_repr = super () . __repr__ ()[ len ( self . __class__ . __name__ ) :] # noqa: E203
+ if len ( super_repr ) == 2 :
+ return f " { self . __class__ . __name__ } ( { default_factory } , )"
+ return f " { self . __class__ . __name__ } ( { default_factory } ," + super_repr [ 1 :]
+
+ def add ( self , name : Any ):
+ r """
+ Add a new default factory to the dictionary.
+
+ Args:
+ name:
+
+ Raises:
+ ValueError: If `default_factory` is None.
+
+ Examples:
+ >>> d = DefaultDict(default_factory=DefaultDict)
+ >>> d.add('d')
+ DefaultDict()
+ >>> d.get('d')
+ DefaultDict()
+ >>> d['n'] = 'chang'
+ >>> d.n
+ 'chang'
+ >>> d.n = 'liu'
+ >>> d['n']
+ 'liu'
+ >>> d = DefaultDict()
+ >>> d.add('a')
+ Traceback (most recent call last):
+ ValueError: Cannot add to a DefaultDict with no default_factory
+ """
+ default_factory = self . getattr ( "default_factory" , None )
+ if default_factory is None :
+ raise ValueError ( "Cannot add to a DefaultDict with no default_factory" )
+ self . set ( name , default_factory ()) # pylint: disable=E1102
+ return self . get ( name )
@@ -1358,8 +1362,7 @@
Source code in chanfig/default_dict.py
- Python 92
- 93
+ Python def add ( self , name : Any ):
- r """
- Add a new default factory to the dictionary.
-
- Args:
- name:
-
- Raises:
- ValueError: If `default_factory` is None.
-
- Examples:
- >>> d = DefaultDict(default_factory=DefaultDict)
- >>> d.add('d')
- DefaultDict()
- >>> d.get('d')
- DefaultDict()
- >>> d['n'] = 'chang'
- >>> d.n
- 'chang'
- >>> d.n = 'liu'
- >>> d['n']
- 'liu'
- >>> d = DefaultDict()
- >>> d.add('a')
- Traceback (most recent call last):
- ValueError: Cannot add to a DefaultDict with no default_factory
- """
- if self . default_factory is None :
- raise ValueError ( "Cannot add to a DefaultDict with no default_factory" )
- self . set ( name , self . default_factory ()) # pylint: disable=E1102
- return self . get ( name )
+122
+123
+124
def add ( self , name : Any ):
+ r """
+ Add a new default factory to the dictionary.
+
+ Args:
+ name:
+
+ Raises:
+ ValueError: If `default_factory` is None.
+
+ Examples:
+ >>> d = DefaultDict(default_factory=DefaultDict)
+ >>> d.add('d')
+ DefaultDict()
+ >>> d.get('d')
+ DefaultDict()
+ >>> d['n'] = 'chang'
+ >>> d.n
+ 'chang'
+ >>> d.n = 'liu'
+ >>> d['n']
+ 'liu'
+ >>> d = DefaultDict()
+ >>> d.add('a')
+ Traceback (most recent call last):
+ ValueError: Cannot add to a DefaultDict with no default_factory
+ """
+ default_factory = self . getattr ( "default_factory" , None )
+ if default_factory is None :
+ raise ValueError ( "Cannot add to a DefaultDict with no default_factory" )
+ self . set ( name , default_factory ()) # pylint: disable=E1102
+ return self . get ( name )
diff --git a/feed_rss_created.xml b/feed_rss_created.xml
index 5598acdf..9ef517f8 100644
--- a/feed_rss_created.xml
+++ b/feed_rss_created.xml
@@ -1 +1 @@
- CHANfiG Easier Configuration https://chanfig.danling.org/CHANfiG Contributors https://github.com/ZhiyuanChen/CHANfiG en Tue, 20 Aug 2024 12:51:13 -0000 Tue, 20 Aug 2024 12:51:13 -0000 1440 MkDocs RSS plugin - v1.15.0 -
About <h1>About</h1><p style="text-align: center;">Developed by DanLing on Earth</p><p>We are a community of developers, designers, and others from around the world who ...</p> https://chanfig.danling.org/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/about/ -
关于 <h1>关于</h1><p style="text-align: center;">由丹灵在地球开发</p><p>我们是一个由开发者、设计人员和其他人员组成的社区,致力于让深度学习技术更加开放。</p><p>我们是一个由个体组成的社区,致力于推动深度学习的可能性边界。</p><p>我们对深度学习及其用户充满激情。</p><p>我们是丹灵。</p> https://chanfig.danling.org/zh/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/zh/about/ -
License <h1>GNU AFFERO GENERAL PUBLIC LICENSE</h1><p>Version 3, 19 November 2007</p><p>Copyright (C) 2007 Free Software Foundation, Inc.<a href="https://fsf.org/">https://fsf.org/</a></p><p>Everyone is permitted...</p> https://chanfig.danling.org/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/about/license/ -
Privacy Notice <p>!!! info "Last Revised Date"</p><pre><code>This notice was last updated on May 04, 2024.</code></pre><h1>Privacy Notice</h1><p>This privacy notice for DanLing Team (also known as DanLin...</p> https://chanfig.danling.org/about/privacy/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/about/privacy/ -
License <p>!!! warning "翻译"</p><pre><code>本文内容为翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://multimolecule.danling.org/about/license)为准。</code></pre><p>...</p> https://chanfig.danling.org/zh/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/zh/about/license/ -
Privacy Notice <p>!!! warning "翻译"</p><pre><code>本文内容为机器翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://chanfig.danling.org/about/privacy)为准。为满...</code></pre> https://chanfig.danling.org/zh/about/privacy/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/zh/about/privacy/ -
CHANfiG <h1>CHANfiG</h1> https://chanfig.danling.org/blog/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/blog/ -
CHANfiG <h1>CHANfiG</h1> https://chanfig.danling.org/zh/blog/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/zh/blog/ -
Home Zhiyuan Chen <p>--8<-- "README.md"</p> https://chanfig.danling.org/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/ -
Config Zhiyuan Chen <h1>Config</h1><p>::: chanfig.config</p> https://chanfig.danling.org/config/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/config/ -
configclass Zhiyuan Chen <h1>configclass</h1><p>::: chanfig.configclasses</p> https://chanfig.danling.org/configclass/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/configclass/ -
DefaultDict Zhiyuan Chen <h1>DefaultDict</h1><p>::: chanfig.DefaultDict</p> https://chanfig.danling.org/default_dict/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/default_dict/ -
FlatDict Zhiyuan Chen <h1>FlatDict</h1><p>::: chanfig.FlatDict</p> https://chanfig.danling.org/flat_dict/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/flat_dict/ -
Functional Zhiyuan Chen <h1>Functional</h1><p>::: chanfig.to_dictoptions:heading_level: 0</p><p>::: chanfig.saveoptions:heading_level: 0</p><p>::: chanfig.loadoptions:heading_level: 0</p><p>::: chan...</p> https://chanfig.danling.org/functional/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/functional/ -
NestedDict Zhiyuan Chen <h1>NestedDict</h1><p>::: chanfig.NestedDict</p> https://chanfig.danling.org/nested_dict/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/nested_dict/ -
ConfigParser Zhiyuan Chen <h1>ConfigParser</h1><p>::: chanfig.ConfigParser</p> https://chanfig.danling.org/parser/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/parser/ -
Registry Zhiyuan Chen <h1>Registry</h1><p>::: chanfig.registry</p> https://chanfig.danling.org/registry/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/registry/ -
Utilities Zhiyuan Chen <h1>Utilities</h1><p>::: chanfig.utils.Singletonoptions:heading_level: 0</p><h2>chanfig.utils.Null</h2><p><code>Null</code> is an instance of [<code>NULL</code>][chanfig.utils.NULL].</p><p>Since the ...</p> https://chanfig.danling.org/utils/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/utils/ -
Variable Zhiyuan Chen <h1>Variable</h1><p>::: chanfig.Variable</p> https://chanfig.danling.org/variable/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/variable/ -
Index Zhiyuan Chen <p>--8<-- "README.zh.md"</p> https://chanfig.danling.org/zh/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/zh/
\ No newline at end of file
+ CHANfiG Easier Configuration https://chanfig.danling.org/CHANfiG Contributors https://github.com/ZhiyuanChen/CHANfiG en Wed, 21 Aug 2024 08:44:07 -0000 Wed, 21 Aug 2024 08:44:07 -0000 1440 MkDocs RSS plugin - v1.15.0 -
About <h1>About</h1><p style="text-align: center;">Developed by DanLing on Earth</p><p>We are a community of developers, designers, and others from around the world who ...</p> https://chanfig.danling.org/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/about/ -
关于 <h1>关于</h1><p style="text-align: center;">由丹灵在地球开发</p><p>我们是一个由开发者、设计人员和其他人员组成的社区,致力于让深度学习技术更加开放。</p><p>我们是一个由个体组成的社区,致力于推动深度学习的可能性边界。</p><p>我们对深度学习及其用户充满激情。</p><p>我们是丹灵。</p> https://chanfig.danling.org/zh/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/zh/about/ -
License <h1>GNU AFFERO GENERAL PUBLIC LICENSE</h1><p>Version 3, 19 November 2007</p><p>Copyright (C) 2007 Free Software Foundation, Inc.<a href="https://fsf.org/">https://fsf.org/</a></p><p>Everyone is permitted...</p> https://chanfig.danling.org/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/about/license/ -
Privacy Notice <p>!!! info "Last Revised Date"</p><pre><code>This notice was last updated on May 04, 2024.</code></pre><h1>Privacy Notice</h1><p>This privacy notice for DanLing Team (also known as DanLin...</p> https://chanfig.danling.org/about/privacy/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/about/privacy/ -
License <p>!!! warning "翻译"</p><pre><code>本文内容为翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://multimolecule.danling.org/about/license)为准。</code></pre><p>...</p> https://chanfig.danling.org/zh/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/zh/about/license/ -
Privacy Notice <p>!!! warning "翻译"</p><pre><code>本文内容为机器翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://chanfig.danling.org/about/privacy)为准。为满...</code></pre> https://chanfig.danling.org/zh/about/privacy/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/zh/about/privacy/ -
CHANfiG <h1>CHANfiG</h1> https://chanfig.danling.org/blog/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/blog/ -
CHANfiG <h1>CHANfiG</h1> https://chanfig.danling.org/zh/blog/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/zh/blog/ -
Home Zhiyuan Chen <p>--8<-- "README.md"</p> https://chanfig.danling.org/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/ -
Config Zhiyuan Chen <h1>Config</h1><p>::: chanfig.config</p> https://chanfig.danling.org/config/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/config/ -
configclass Zhiyuan Chen <h1>configclass</h1><p>::: chanfig.configclasses</p> https://chanfig.danling.org/configclass/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/configclass/ -
DefaultDict Zhiyuan Chen <h1>DefaultDict</h1><p>::: chanfig.DefaultDict</p> https://chanfig.danling.org/default_dict/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/default_dict/ -
FlatDict Zhiyuan Chen <h1>FlatDict</h1><p>::: chanfig.FlatDict</p> https://chanfig.danling.org/flat_dict/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/flat_dict/ -
Functional Zhiyuan Chen <h1>Functional</h1><p>::: chanfig.to_dictoptions:heading_level: 0</p><p>::: chanfig.saveoptions:heading_level: 0</p><p>::: chanfig.loadoptions:heading_level: 0</p><p>::: chan...</p> https://chanfig.danling.org/functional/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/functional/ -
NestedDict Zhiyuan Chen <h1>NestedDict</h1><p>::: chanfig.NestedDict</p> https://chanfig.danling.org/nested_dict/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/nested_dict/ -
ConfigParser Zhiyuan Chen <h1>ConfigParser</h1><p>::: chanfig.ConfigParser</p> https://chanfig.danling.org/parser/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/parser/ -
Registry Zhiyuan Chen <h1>Registry</h1><p>::: chanfig.registry</p> https://chanfig.danling.org/registry/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/registry/ -
Utilities Zhiyuan Chen <h1>Utilities</h1><p>::: chanfig.utils.Singletonoptions:heading_level: 0</p><h2>chanfig.utils.Null</h2><p><code>Null</code> is an instance of [<code>NULL</code>][chanfig.utils.NULL].</p><p>Since the ...</p> https://chanfig.danling.org/utils/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/utils/ -
Variable Zhiyuan Chen <h1>Variable</h1><p>::: chanfig.Variable</p> https://chanfig.danling.org/variable/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/variable/ -
Index Zhiyuan Chen <p>--8<-- "README.zh.md"</p> https://chanfig.danling.org/zh/ Wed, 04 May 2022 00:00:00 +0000 CHANfiG https://chanfig.danling.org/zh/
\ No newline at end of file
diff --git a/feed_rss_updated.xml b/feed_rss_updated.xml
index 7c786673..7ebae7ee 100644
--- a/feed_rss_updated.xml
+++ b/feed_rss_updated.xml
@@ -1 +1 @@
- CHANfiG Easier Configuration https://chanfig.danling.org/CHANfiG Contributors https://github.com/ZhiyuanChen/CHANfiG en Tue, 20 Aug 2024 12:51:13 -0000 Tue, 20 Aug 2024 12:51:13 -0000 1440 MkDocs RSS plugin - v1.15.0 -
About <h1>About</h1><p style="text-align: center;">Developed by DanLing on Earth</p><p>We are a community of developers, designers, and others from around the world who ...</p> https://chanfig.danling.org/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/about/ -
Privacy Notice <p>!!! info "Last Revised Date"</p><pre><code>This notice was last updated on May 04, 2024.</code></pre><h1>Privacy Notice</h1><p>This privacy notice for DanLing Team (also known as DanLin...</p> https://chanfig.danling.org/about/privacy/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/about/privacy/ -
关于 <h1>关于</h1><p style="text-align: center;">由丹灵在地球开发</p><p>我们是一个由开发者、设计人员和其他人员组成的社区,致力于让深度学习技术更加开放。</p><p>我们是一个由个体组成的社区,致力于推动深度学习的可能性边界。</p><p>我们对深度学习及其用户充满激情。</p><p>我们是丹灵。</p> https://chanfig.danling.org/zh/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/zh/about/ -
Privacy Notice <p>!!! warning "翻译"</p><pre><code>本文内容为机器翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://chanfig.danling.org/about/privacy)为准。为满...</code></pre> https://chanfig.danling.org/zh/about/privacy/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/zh/about/privacy/ -
License <h1>GNU AFFERO GENERAL PUBLIC LICENSE</h1><p>Version 3, 19 November 2007</p><p>Copyright (C) 2007 Free Software Foundation, Inc.<a href="https://fsf.org/">https://fsf.org/</a></p><p>Everyone is permitted...</p> https://chanfig.danling.org/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/about/license/ -
License <p>!!! warning "翻译"</p><pre><code>本文内容为翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://multimolecule.danling.org/about/license)为准。</code></pre><p>...</p> https://chanfig.danling.org/zh/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/zh/about/license/ -
Registry Zhiyuan Chen <h1>Registry</h1><p>::: chanfig.registry</p> https://chanfig.danling.org/registry/ Thu, 28 Mar 2024 11:05:48 +0000 CHANfiG https://chanfig.danling.org/registry/ -
Registry Zhiyuan Chen <h1>Registry</h1><p>::: chanfig.registry</p> https://chanfig.danling.org/zh/registry/ Thu, 28 Mar 2024 11:05:48 +0000 CHANfiG https://chanfig.danling.org/zh/registry/ -
configclass Zhiyuan Chen <h1>configclass</h1><p>::: chanfig.configclasses</p> https://chanfig.danling.org/configclass/ Fri, 08 Mar 2024 08:01:02 +0000 CHANfiG https://chanfig.danling.org/configclass/ -
configclass Zhiyuan Chen <h1>configclass</h1><p>::: chanfig.configclasses</p> https://chanfig.danling.org/zh/configclass/ Fri, 08 Mar 2024 08:01:02 +0000 CHANfiG https://chanfig.danling.org/zh/configclass/ -
Functional Zhiyuan Chen <h1>Functional</h1><p>::: chanfig.to_dictoptions:heading_level: 0</p><p>::: chanfig.saveoptions:heading_level: 0</p><p>::: chanfig.loadoptions:heading_level: 0</p><p>::: chan...</p> https://chanfig.danling.org/functional/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/functional/ -
ConfigParser Zhiyuan Chen <h1>ConfigParser</h1><p>::: chanfig.ConfigParser</p> https://chanfig.danling.org/parser/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/parser/ -
Utilities Zhiyuan Chen <h1>Utilities</h1><p>::: chanfig.utils.Singletonoptions:heading_level: 0</p><h2>chanfig.utils.Null</h2><p><code>Null</code> is an instance of [<code>NULL</code>][chanfig.utils.NULL].</p><p>Since the ...</p> https://chanfig.danling.org/utils/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/utils/ -
Functional Zhiyuan Chen <h1>Functional</h1><p>::: chanfig.to_dictoptions:heading_level: 0</p><p>::: chanfig.saveoptions:heading_level: 0</p><p>::: chanfig.loadoptions:heading_level: 0</p><p>::: chan...</p> https://chanfig.danling.org/zh/functional/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/zh/functional/ -
ConfigParser Zhiyuan Chen <h1>ConfigParser</h1><p>::: chanfig.ConfigParser</p> https://chanfig.danling.org/zh/parser/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/zh/parser/ -
Utilities Zhiyuan Chen <h1>Utilities</h1><p>::: chanfig.utils.Singletonoptions:heading_level: 0</p><h2>chanfig.utils.Null</h2><p><code>Null</code> is an instance of [<code>NULL</code>][chanfig.utils.NULL].</p><p>Since the ...</p> https://chanfig.danling.org/zh/utils/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/zh/utils/ -
Home Zhiyuan Chen <p>--8<-- "README.md"</p> https://chanfig.danling.org/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/ -
Config Zhiyuan Chen <h1>Config</h1><p>::: chanfig.config</p> https://chanfig.danling.org/config/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/config/ -
DefaultDict Zhiyuan Chen <h1>DefaultDict</h1><p>::: chanfig.DefaultDict</p> https://chanfig.danling.org/default_dict/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/default_dict/ -
FlatDict Zhiyuan Chen <h1>FlatDict</h1><p>::: chanfig.FlatDict</p> https://chanfig.danling.org/flat_dict/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/flat_dict/
\ No newline at end of file
+ CHANfiG Easier Configuration https://chanfig.danling.org/CHANfiG Contributors https://github.com/ZhiyuanChen/CHANfiG en Wed, 21 Aug 2024 08:44:07 -0000 Wed, 21 Aug 2024 08:44:07 -0000 1440 MkDocs RSS plugin - v1.15.0 -
About <h1>About</h1><p style="text-align: center;">Developed by DanLing on Earth</p><p>We are a community of developers, designers, and others from around the world who ...</p> https://chanfig.danling.org/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/about/ -
Privacy Notice <p>!!! info "Last Revised Date"</p><pre><code>This notice was last updated on May 04, 2024.</code></pre><h1>Privacy Notice</h1><p>This privacy notice for DanLing Team (also known as DanLin...</p> https://chanfig.danling.org/about/privacy/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/about/privacy/ -
关于 <h1>关于</h1><p style="text-align: center;">由丹灵在地球开发</p><p>我们是一个由开发者、设计人员和其他人员组成的社区,致力于让深度学习技术更加开放。</p><p>我们是一个由个体组成的社区,致力于推动深度学习的可能性边界。</p><p>我们对深度学习及其用户充满激情。</p><p>我们是丹灵。</p> https://chanfig.danling.org/zh/about/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/zh/about/ -
Privacy Notice <p>!!! warning "翻译"</p><pre><code>本文内容为机器翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://chanfig.danling.org/about/privacy)为准。为满...</code></pre> https://chanfig.danling.org/zh/about/privacy/ Mon, 29 Jul 2024 20:39:24 +0000 CHANfiG https://chanfig.danling.org/zh/about/privacy/ -
License <h1>GNU AFFERO GENERAL PUBLIC LICENSE</h1><p>Version 3, 19 November 2007</p><p>Copyright (C) 2007 Free Software Foundation, Inc.<a href="https://fsf.org/">https://fsf.org/</a></p><p>Everyone is permitted...</p> https://chanfig.danling.org/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/about/license/ -
License <p>!!! warning "翻译"</p><pre><code>本文内容为翻译版本,旨在为用户提供方便。我们已经尽力确保翻译的准确性。但请注意,翻译内容可能包含错误,仅供参考。请以英文[原文](https://multimolecule.danling.org/about/license)为准。</code></pre><p>...</p> https://chanfig.danling.org/zh/about/license/ Mon, 08 Jul 2024 05:11:39 +0000 CHANfiG https://chanfig.danling.org/zh/about/license/ -
Registry Zhiyuan Chen <h1>Registry</h1><p>::: chanfig.registry</p> https://chanfig.danling.org/registry/ Thu, 28 Mar 2024 11:05:48 +0000 CHANfiG https://chanfig.danling.org/registry/ -
Registry Zhiyuan Chen <h1>Registry</h1><p>::: chanfig.registry</p> https://chanfig.danling.org/zh/registry/ Thu, 28 Mar 2024 11:05:48 +0000 CHANfiG https://chanfig.danling.org/zh/registry/ -
configclass Zhiyuan Chen <h1>configclass</h1><p>::: chanfig.configclasses</p> https://chanfig.danling.org/configclass/ Fri, 08 Mar 2024 08:01:02 +0000 CHANfiG https://chanfig.danling.org/configclass/ -
configclass Zhiyuan Chen <h1>configclass</h1><p>::: chanfig.configclasses</p> https://chanfig.danling.org/zh/configclass/ Fri, 08 Mar 2024 08:01:02 +0000 CHANfiG https://chanfig.danling.org/zh/configclass/ -
Functional Zhiyuan Chen <h1>Functional</h1><p>::: chanfig.to_dictoptions:heading_level: 0</p><p>::: chanfig.saveoptions:heading_level: 0</p><p>::: chanfig.loadoptions:heading_level: 0</p><p>::: chan...</p> https://chanfig.danling.org/functional/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/functional/ -
ConfigParser Zhiyuan Chen <h1>ConfigParser</h1><p>::: chanfig.ConfigParser</p> https://chanfig.danling.org/parser/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/parser/ -
Utilities Zhiyuan Chen <h1>Utilities</h1><p>::: chanfig.utils.Singletonoptions:heading_level: 0</p><h2>chanfig.utils.Null</h2><p><code>Null</code> is an instance of [<code>NULL</code>][chanfig.utils.NULL].</p><p>Since the ...</p> https://chanfig.danling.org/utils/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/utils/ -
Functional Zhiyuan Chen <h1>Functional</h1><p>::: chanfig.to_dictoptions:heading_level: 0</p><p>::: chanfig.saveoptions:heading_level: 0</p><p>::: chanfig.loadoptions:heading_level: 0</p><p>::: chan...</p> https://chanfig.danling.org/zh/functional/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/zh/functional/ -
ConfigParser Zhiyuan Chen <h1>ConfigParser</h1><p>::: chanfig.ConfigParser</p> https://chanfig.danling.org/zh/parser/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/zh/parser/ -
Utilities Zhiyuan Chen <h1>Utilities</h1><p>::: chanfig.utils.Singletonoptions:heading_level: 0</p><h2>chanfig.utils.Null</h2><p><code>Null</code> is an instance of [<code>NULL</code>][chanfig.utils.NULL].</p><p>Since the ...</p> https://chanfig.danling.org/zh/utils/ Wed, 26 Jul 2023 17:37:04 +0000 CHANfiG https://chanfig.danling.org/zh/utils/ -
Home Zhiyuan Chen <p>--8<-- "README.md"</p> https://chanfig.danling.org/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/ -
Config Zhiyuan Chen <h1>Config</h1><p>::: chanfig.config</p> https://chanfig.danling.org/config/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/config/ -
DefaultDict Zhiyuan Chen <h1>DefaultDict</h1><p>::: chanfig.DefaultDict</p> https://chanfig.danling.org/default_dict/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/default_dict/ -
FlatDict Zhiyuan Chen <h1>FlatDict</h1><p>::: chanfig.FlatDict</p> https://chanfig.danling.org/flat_dict/ Thu, 20 Jul 2023 17:14:16 +0000 CHANfiG https://chanfig.danling.org/flat_dict/
\ No newline at end of file
diff --git a/flat_dict/index.html b/flat_dict/index.html
index d8b274af..05e640b0 100644
--- a/flat_dict/index.html
+++ b/flat_dict/index.html
@@ -1050,6 +1050,15 @@
+
+
+
+
+
+ move_class_attributes
+
+
+
@@ -1443,7 +1452,6 @@ FlatDictindent
- int
class FlatDict ( dict , metaclass = Dict ):
r """
`FlatDict` with attribute-style access.
@@ -2970,7 +3005,7 @@ FlatDict
# pylint: disable=R0904
- indent : int = 2
+ indent = 2
def __init__ ( self , * args : Any , ** kwargs : Any ) -> None :
if len ( args ) == 1 :
@@ -2981,1345 +3016,1372 @@ FlatDict arg = vars ( arg )
args = ( arg ,)
super () . __init__ ( * args , ** kwargs )
-
- def __post_init__ ( self , * args , ** kwargs ) -> None :
- pass
-
- def __getattribute__ ( self , name : Any ) -> Any :
- if ( name not in ( "getattr" ,) and not ( name . startswith ( "__" ) and name . endswith ( "__" ))) and name in self :
- if name in dir ( self . __class__ ):
- value = super () . __getattribute__ ( name )
- if isinstance ( value , ( property , staticmethod , classmethod )) or callable ( value ):
- return value
- return self . get ( name )
- return super () . __getattribute__ ( name )
+ self . move_class_attributes ()
+
+ def move_class_attributes ( self , recursive : bool = True ) -> Self :
+ r """
+ Move class attributes to instance.
+
+ Args:
+ recursive:
+
+ Returns:
+ self:
+ """
- def get ( self , name : Any , default : Any = None ) -> Any :
- r """
- Get value from `FlatDict`.
-
- Args:
- name:
- default:
+ def move_cls_attributes ( cls : type ) -> Mapping :
+ attributes = {}
+ for k in get_annotations ( cls ) . keys ():
+ if k in cls . __dict__ :
+ attributes [ k ] = cls . __dict__ [ k ]
+ delattr ( cls , k )
+ return attributes
- Returns:
- value:
- If `FlatDict` does not contain `name`, return `default`.
-
- Raises:
- KeyError: If `FlatDict` does not contain `name` and `default` is not specified.
- TypeError: If `name` is not hashable.
-
- Examples:
- >>> d = FlatDict(d=1013)
- >>> d.get('d')
- 1013
- >>> d['d']
- 1013
- >>> d.d
- 1013
- >>> d.get('d', None)
- 1013
- >>> d.get('f', 2)
- 2
- >>> d.get('f')
- >>> d.get('f', Null)
- Traceback (most recent call last):
- KeyError: 'f'
- """
-
- if name in self :
- return dict . __getitem__ ( self , name )
- if default is not Null :
- return default
- return self . __missing__ ( name )
-
- def __getitem__ ( self , name : Any ) -> Any :
- return self . get ( name , default = Null )
+ if recursive :
+ for cls in self . __class__ . __mro__ :
+ self . merge ( move_cls_attributes ( cls ), overwrite = False )
+ else :
+ self . merge ( move_cls_attributes ( self . __class__ ), overwrite = False )
+ return self
+
+ def __post_init__ ( self , * args , ** kwargs ) -> None :
+ pass
+
+ def __getattribute__ ( self , name : Any ) -> Any :
+ if ( name not in ( "getattr" ,) and not ( name . startswith ( "__" ) and name . endswith ( "__" ))) and name in self :
+ if name in dir ( self . __class__ ):
+ value = super () . __getattribute__ ( name )
+ if isinstance ( value , ( property , staticmethod , classmethod )) or callable ( value ):
+ return value
+ return self . get ( name )
+ return super () . __getattribute__ ( name )
+
+ def get ( self , name : Any , default : Any = None ) -> Any :
+ r """
+ Get value from `FlatDict`.
+
+ Args:
+ name:
+ default:
+
+ Returns:
+ value:
+ If `FlatDict` does not contain `name`, return `default`.
+
+ Raises:
+ KeyError: If `FlatDict` does not contain `name` and `default` is not specified.
+ TypeError: If `name` is not hashable.
- def __getattr__ ( self , name : Any ) -> Any :
- try :
- return self . get ( name , default = Null )
- except KeyError :
- raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
-
- def set ( self , name : Any , value : Any ) -> None :
- r """
- Set value of `FlatDict`.
-
- Args:
- name:
- value:
-
- Examples:
- >>> d = FlatDict()
- >>> d.set('d', 1013)
- >>> d.get('d')
- 1013
- >>> d['n'] = 'chang'
- >>> d.n
- 'chang'
- >>> d.n = 'liu'
- >>> d['n']
- 'liu'
- """
+ Examples:
+ >>> d = FlatDict(d=1013)
+ >>> d.get('d')
+ 1013
+ >>> d['d']
+ 1013
+ >>> d.d
+ 1013
+ >>> d.get('d', None)
+ 1013
+ >>> d.get('f', 2)
+ 2
+ >>> d.get('f')
+ >>> d.get('f', Null)
+ Traceback (most recent call last):
+ KeyError: 'f'
+ """
+
+ if name in self :
+ return dict . __getitem__ ( self , name )
+ if default is not Null :
+ return default
+ return self . __missing__ ( name )
+
+ def __getitem__ ( self , name : Any ) -> Any :
+ return self . get ( name , default = Null )
- if name is Null :
- raise ValueError ( "name must not be null" )
- if name in self and isinstance ( self . get ( name ), Variable ):
- self . get ( name ) . set ( value )
- else :
- dict . __setitem__ ( self , name , value )
-
- def __setitem__ ( self , name : Any , value : Any ) -> None :
- self . set ( name , value )
+ def __getattr__ ( self , name : Any ) -> Any :
+ try :
+ return self . get ( name , default = Null )
+ except KeyError :
+ raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
+
+ def set ( self , name : Any , value : Any ) -> None :
+ r """
+ Set value of `FlatDict`.
- def __setattr__ ( self , name : Any , value : Any ) -> None :
- self . set ( name , value )
-
- def delete ( self , name : Any ) -> None :
- r """
- Delete value from `FlatDict`.
-
- Args:
- name:
-
- Examples:
- >>> d = FlatDict(d=1016, n='chang')
- >>> d.d
- 1016
- >>> d.n
- 'chang'
- >>> d.delete('d')
- >>> d.d
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'd'
- >>> del d.n
- >>> d.n
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'n'
- >>> del d.f
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'f'
- """
-
- dict . __delitem__ ( self , name )
-
- def __delitem__ ( self , name : Any ) -> None :
- return self . delete ( name )
+ Args:
+ name:
+ value:
+
+ Examples:
+ >>> d = FlatDict()
+ >>> d.set('d', 1013)
+ >>> d.get('d')
+ 1013
+ >>> d['n'] = 'chang'
+ >>> d.n
+ 'chang'
+ >>> d.n = 'liu'
+ >>> d['n']
+ 'liu'
+ """
+
+ if name is Null :
+ raise ValueError ( "name must not be null" )
+ if name in self and isinstance ( self . get ( name ), Variable ):
+ self . get ( name ) . set ( value )
+ else :
+ dict . __setitem__ ( self , name , value )
+
+ def __setitem__ ( self , name : Any , value : Any ) -> None :
+ self . set ( name , value )
+
+ def __setattr__ ( self , name : Any , value : Any ) -> None :
+ self . set ( name , value )
+
+ def delete ( self , name : Any ) -> None :
+ r """
+ Delete value from `FlatDict`.
- def __delattr__ ( self , name : Any ) -> None :
- try :
- self . delete ( name )
- except KeyError :
- raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
-
- def __missing__ ( self , name : Any ) -> Any : # pylint: disable=R1710
- raise KeyError ( name )
-
- def validate ( self ) -> None :
- r """
- Validate `FlatDict`.
-
- Raises:
- TypeError: If value is not of the type declared in class annotations.
- TypeError: If `Variable` has invalid type.
- ValueError: If `Variable` has invalid value.
-
- Examples:
- >>> d = FlatDict(d=Variable(1016, type=int), n=Variable('chang', validator=lambda x: x.islower()))
- >>> d = FlatDict(d=Variable(1016, type=str), n=Variable('chang', validator=lambda x: x.islower()))
- Traceback (most recent call last):
- TypeError: 'd' has invalid type. Value 1016 is not of type <class 'str'>.
- >>> d = FlatDict(d=Variable(1016, type=int), n=Variable('chang', validator=lambda x: x.isupper()))
- Traceback (most recent call last):
- ValueError: 'n' has invalid value. Value chang is not valid.
- """
-
- self . _validate ( self )
-
- @staticmethod
- def _validate ( obj ) -> None :
- if isinstance ( obj , FlatDict ):
- annotations = get_annotations ( obj )
- for name , value in obj . items ():
- if annotations and name in annotations and not isvalid ( value , annotations [ name ]):
- raise TypeError ( f "' { name } ' has invalid type. Value { value } is not of type { annotations [ name ] } ." )
- if isinstance ( value , Variable ):
- try :
- value . validate ()
- except TypeError as exc :
- raise TypeError ( f "' { name } ' has invalid type. { exc } " ) from None
- except ValueError as exc :
- raise ValueError ( f "' { name } ' has invalid value. { exc } " ) from None
+ Args:
+ name:
+
+ Examples:
+ >>> d = FlatDict(d=1016, n='chang')
+ >>> d.d
+ 1016
+ >>> d.n
+ 'chang'
+ >>> d.delete('d')
+ >>> d.d
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'd'
+ >>> del d.n
+ >>> d.n
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'n'
+ >>> del d.f
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'f'
+ """
+
+ dict . __delitem__ ( self , name )
+
+ def __delitem__ ( self , name : Any ) -> None :
+ return self . delete ( name )
+
+ def __delattr__ ( self , name : Any ) -> None :
+ try :
+ self . delete ( name )
+ except KeyError :
+ raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
+
+ def __missing__ ( self , name : Any ) -> Any : # pylint: disable=R1710
+ raise KeyError ( name )
+
+ def validate ( self ) -> None :
+ r """
+ Validate `FlatDict`.
+
+ Raises:
+ TypeError: If value is not of the type declared in class annotations.
+ TypeError: If `Variable` has invalid type.
+ ValueError: If `Variable` has invalid value.
- def getattr ( self , name : str , default : Any = Null ) -> Any :
- r """
- Get attribute of `FlatDict`.
-
- Note that it won't retrieve value in `FlatDict`,
-
- Args:
- name:
- default:
+ Examples:
+ >>> d = FlatDict(d=Variable(1016, type=int), n=Variable('chang', validator=lambda x: x.islower()))
+ >>> d = FlatDict(d=Variable(1016, type=str), n=Variable('chang', validator=lambda x: x.islower()))
+ Traceback (most recent call last):
+ TypeError: 'd' has invalid type. Value 1016 is not of type <class 'str'>.
+ >>> d = FlatDict(d=Variable(1016, type=int), n=Variable('chang', validator=lambda x: x.isupper()))
+ Traceback (most recent call last):
+ ValueError: 'n' has invalid value. Value chang is not valid.
+ """
- Returns:
- value: If `FlatDict` does not contain `name`, return `default`.
-
- Raises:
- AttributeError: If `FlatDict` does not contain `name` and `default` is not specified.
-
- Examples:
- >>> d = FlatDict(a=1)
- >>> d.get('a')
- 1
- >>> d.getattr('a')
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'a'
- >>> d.getattr('b', 2)
- 2
- >>> d.setattr('b', 3)
- >>> d.getattr('b')
- 3
- """
-
- try :
- if name in self . __dict__ :
- return self . __dict__ [ name ]
- for cls in self . __class__ . __mro__ :
- if name in cls . __dict__ :
- return cls . __dict__ [ name ]
- return super () . getattr ( name , default ) # type: ignore[misc]
- except AttributeError :
- if default is not Null :
- return default
- raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
-
- def setattr ( self , name : str , value : Any ) -> None :
- r """
- Set attribute of `FlatDict`.
-
- Note that it won't alter values in `FlatDict`.
-
- Args:
- name:
- value:
-
- Warns:
- RuntimeWarning: If name already exists in `FlatDict`.
-
- Examples:
- >>> d = FlatDict()
- >>> d.setattr('attr', 'value')
- >>> d.getattr('attr')
- 'value'
- >>> d.set('d', 1013)
- >>> d.setattr('d', 1031) # RuntimeWarning: d already exists in FlatDict.
- >>> d.get('d')
- 1013
- >>> d.d
- 1013
- >>> d.getattr('d')
- 1031
- """
-
- if name in self :
- warn (
- f " { name } already exists in { self . __class__ . __name__ } . \n "
- f "Users must call ` { self . __class__ . __name__ } .getattr()` to retrieve conflicting attribute value." ,
- RuntimeWarning ,
- )
- self . __dict__ [ name ] = value
-
- def delattr ( self , name : str ) -> None :
- r """
- Delete attribute of `FlatDict`.
+ self . _validate ( self )
+
+ @staticmethod
+ def _validate ( obj ) -> None :
+ if isinstance ( obj , FlatDict ):
+ annotations = get_annotations ( obj )
+ for name , value in obj . items ():
+ if annotations and name in annotations and not isvalid ( value , annotations [ name ]):
+ raise TypeError ( f "' { name } ' has invalid type. Value { value } is not of type { annotations [ name ] } ." )
+ if isinstance ( value , Variable ):
+ try :
+ value . validate ()
+ except TypeError as exc :
+ raise TypeError ( f "' { name } ' has invalid type. { exc } " ) from None
+ except ValueError as exc :
+ raise ValueError ( f "' { name } ' has invalid value. { exc } " ) from None
+
+ def getattr ( self , name : str , default : Any = Null ) -> Any :
+ r """
+ Get attribute of `FlatDict`.
+
+ Note that it won't retrieve value in `FlatDict`,
+
+ Args:
+ name:
+ default:
+
+ Returns:
+ value: If `FlatDict` does not contain `name`, return `default`.
+
+ Raises:
+ AttributeError: If `FlatDict` does not contain `name` and `default` is not specified.
+
+ Examples:
+ >>> d = FlatDict(a=1)
+ >>> d.get('a')
+ 1
+ >>> d.getattr('a')
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'a'
+ >>> d.getattr('b', 2)
+ 2
+ >>> d.setattr('b', 3)
+ >>> d.getattr('b')
+ 3
+ """
+
+ try :
+ if name in self . __dict__ :
+ return self . __dict__ [ name ]
+ for cls in self . __class__ . __mro__ :
+ if name in cls . __dict__ :
+ return cls . __dict__ [ name ]
+ return super () . getattr ( name , default ) # type: ignore[misc]
+ except AttributeError :
+ if default is not Null :
+ return default
+ raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
+
+ def setattr ( self , name : str , value : Any ) -> None :
+ r """
+ Set attribute of `FlatDict`.
+
+ Note that it won't alter values in `FlatDict`.
+
+ Args:
+ name:
+ value:
+
+ Warns:
+ RuntimeWarning: If name already exists in `FlatDict`.
- Note that it won't delete values in `FlatDict`.
-
- Args:
- name:
-
- Examples:
- >>> d = FlatDict()
- >>> d.setattr('name', 'chang')
- >>> d.getattr('name')
- 'chang'
- >>> d.delattr('name')
- >>> d.getattr('name')
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'name'
- """
-
- del self . __dict__ [ name ]
-
- def hasattr ( self , name : str ) -> bool :
- r """
- Determine if an attribute exists in `FlatDict`.
-
- Args:
- name:
-
- Returns:
- (bool):
-
- Examples:
- >>> d = FlatDict()
- >>> d.setattr('name', 'chang')
- >>> d.hasattr('name')
- True
- >>> d.delattr('name')
- >>> d.hasattr('name')
- False
- """
-
- try :
- if name in self . __dict__ or name in self . __class__ . __dict__ :
- return True
- return super () . hasattr ( name ) # type: ignore[misc]
- except AttributeError :
- return False
+ Examples:
+ >>> d = FlatDict()
+ >>> d.setattr('attr', 'value')
+ >>> d.getattr('attr')
+ 'value'
+ >>> d.set('d', 1013)
+ >>> d.setattr('d', 1031) # RuntimeWarning: d already exists in FlatDict.
+ >>> d.get('d')
+ 1013
+ >>> d.d
+ 1013
+ >>> d.getattr('d')
+ 1031
+ """
+
+ if name in self :
+ warn (
+ f " { name } already exists in { self . __class__ . __name__ } . \n "
+ f "Users must call ` { self . __class__ . __name__ } .getattr()` to retrieve conflicting attribute value." ,
+ RuntimeWarning ,
+ )
+ self . __dict__ [ name ] = value
+
+ def delattr ( self , name : str ) -> None :
+ r """
+ Delete attribute of `FlatDict`.
+
+ Note that it won't delete values in `FlatDict`.
+
+ Args:
+ name:
+
+ Examples:
+ >>> d = FlatDict()
+ >>> d.setattr('name', 'chang')
+ >>> d.getattr('name')
+ 'chang'
+ >>> d.delattr('name')
+ >>> d.getattr('name')
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'name'
+ """
+
+ del self . __dict__ [ name ]
- def dict ( self , flatten : bool = False ) -> Mapping | Sequence | Set :
+ def hasattr ( self , name : str ) -> bool :
r """
- Convert `FlatDict` to other `Mapping`.
+ Determine if an attribute exists in `FlatDict`.
Args:
- flatten: Whether to flatten [`NestedDict`][chanfig.NestedDict].
+ name:
Returns:
- (Mapping):
+ (bool):
- See Also:
- [`to_dict`][chanfig.flat_dict.to_dict]: Implementation of `dict`.
-
- **Alias**:
-
- + `to_dict`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- return to_dict ( self , flatten )
-
- def to_dict ( self , flatten : bool = False ) -> Mapping | Sequence | Set :
- r """
- Alias of [`dict`][chanfig.FlatDict.dict].
- """
-
- return self . dict ( flatten )
-
- @classmethod
- def from_dict ( cls , obj : Mapping | Sequence ) -> Any : # pylint: disable=R0911
- r """
- Convert `Mapping` or `Sequence` to `FlatDict`.
+ Examples:
+ >>> d = FlatDict()
+ >>> d.setattr('name', 'chang')
+ >>> d.hasattr('name')
+ True
+ >>> d.delattr('name')
+ >>> d.hasattr('name')
+ False
+ """
+
+ try :
+ if name in self . __dict__ or name in self . __class__ . __dict__ :
+ return True
+ return super () . hasattr ( name ) # type: ignore[misc]
+ except AttributeError :
+ return False
+
+ def dict ( self , flatten : bool = False ) -> Mapping | Sequence | Set :
+ r """
+ Convert `FlatDict` to other `Mapping`.
+
+ Args:
+ flatten: Whether to flatten [`NestedDict`][chanfig.NestedDict].
+
+ Returns:
+ (Mapping):
- Examples:
- >>> FlatDict.from_dict({'a': 1, 'b': 2, 'c': 3})
- FlatDict(
- ('a'): 1
- ('b'): 2
- ('c'): 3
- )
- >>> FlatDict.from_dict([('a', 1), ('b', 2), ('c', 3)])
- FlatDict(
- ('a'): 1
- ('b'): 2
- ('c'): 3
- )
- >>> FlatDict.from_dict([{'a': 1}, {'b': 2}, {'c': 3}])
- [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
- >>> FlatDict.from_dict({1, 2, 3})
- Traceback (most recent call last):
- TypeError: Expected Mapping or Sequence, but got <class 'set'>.
+ See Also:
+ [`to_dict`][chanfig.flat_dict.to_dict]: Implementation of `dict`.
+
+ **Alias**:
+
+ + `to_dict`
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ return to_dict ( self , flatten )
+
+ def to_dict ( self , flatten : bool = False ) -> Mapping | Sequence | Set :
+ r """
+ Alias of [`dict`][chanfig.FlatDict.dict].
"""
- if obj is None :
- return cls ()
- if issubclass ( cls , FlatDict ):
- cls = cls . empty # type: ignore[assignment] # pylint: disable=W0642
- if isinstance ( obj , Mapping ):
- return cls ( obj )
- if isinstance ( obj , Sequence ):
- try :
- return cls ( obj )
- except ValueError :
- return [ cls ( json ) for json in obj ]
- raise TypeError ( f "Expected Mapping or Sequence, but got { type ( obj ) } ." )
-
- def sort ( self , key : Callable | None = None , reverse : bool = False ) -> Self :
- r """
- Sort `FlatDict`.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.sort().dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> d = FlatDict(b=2, c=3, a=1)
- >>> d.sort().dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> a = [1]
- >>> d = FlatDict(z=0, a=a)
- >>> a.append(2)
- >>> d.sort().dict()
- {'a': [1, 2], 'z': 0}
- """
-
- items = sorted ( self . items (), key = key , reverse = reverse )
- self . clear ()
- for k , v in items : # pylint: disable=C0103
- self [ k ] = v
- return self
+ return self . dict ( flatten )
+
+ @classmethod
+ def from_dict ( cls , obj : Mapping | Sequence ) -> Any : # pylint: disable=R0911
+ r """
+ Convert `Mapping` or `Sequence` to `FlatDict`.
+
+ Examples:
+ >>> FlatDict.from_dict({'a': 1, 'b': 2, 'c': 3})
+ FlatDict(
+ ('a'): 1
+ ('b'): 2
+ ('c'): 3
+ )
+ >>> FlatDict.from_dict([('a', 1), ('b', 2), ('c', 3)])
+ FlatDict(
+ ('a'): 1
+ ('b'): 2
+ ('c'): 3
+ )
+ >>> FlatDict.from_dict([{'a': 1}, {'b': 2}, {'c': 3}])
+ [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
+ >>> FlatDict.from_dict({1, 2, 3})
+ Traceback (most recent call last):
+ TypeError: Expected Mapping or Sequence, but got <class 'set'>.
+ """
+
+ if obj is None :
+ return cls ()
+ if issubclass ( cls , FlatDict ):
+ cls = cls . empty # type: ignore[assignment] # pylint: disable=W0642
+ if isinstance ( obj , Mapping ):
+ return cls ( obj )
+ if isinstance ( obj , Sequence ):
+ try :
+ return cls ( obj )
+ except ValueError :
+ return [ cls ( json ) for json in obj ]
+ raise TypeError ( f "Expected Mapping or Sequence, but got { type ( obj ) } ." )
- def interpolate ( # pylint: disable=R0912
- self , use_variable : bool = True , interpolators : MutableMapping | None = None , unsafe_eval : bool = False
- ) -> Self :
- r """
- Perform Variable interpolation.
-
- Variable interpolation allows you to set the value of one key to be the value of another key easily.
-
- Args:
- use_variable: Whether to convert values to `Variable` objects.
- interpolators: Mapping contains values for interpolation. Defaults to `self`.
- unsafe_eval: Whether to evaluate interpolated values.
-
- Raises:
- ValueError: If value is not interpolatable.
- ValueError: If reference to itself.
- ValueError: If has circular reference.
-
- See Also:
- [Variable][`chanfig.Variable`]: Mutable wrapper of immutable objects.
+ def sort ( self , key : Callable | None = None , reverse : bool = False ) -> Self :
+ r """
+ Sort `FlatDict`.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.sort().dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> d = FlatDict(b=2, c=3, a=1)
+ >>> d.sort().dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> a = [1]
+ >>> d = FlatDict(z=0, a=a)
+ >>> a.append(2)
+ >>> d.sort().dict()
+ {'a': [1, 2], 'z': 0}
+ """
- Examples:
- >>> d = FlatDict(a=1, b="${a}", c="${a}.${b}")
- >>> d.dict()
- {'a': 1, 'b': '${a}', 'c': '${a}.${b}'}
- >>> d.interpolate(unsafe_eval=True).dict()
- {'a': 1, 'b': 1, 'c': 1.1}
- >>> d = FlatDict(a=1, b="${a}", c="${a}.${b}")
- >>> d.dict()
- {'a': 1, 'b': '${a}', 'c': '${a}.${b}'}
- >>> d.interpolate().dict()
- {'a': 1, 'b': 1, 'c': '1.1'}
- >>> isinstance(d.a, Variable)
- True
- >>> d.a += 1
- >>> d.dict()
- {'a': 2, 'b': 2, 'c': '1.1'}
- >>> d.a is d.b
- True
- >>> d.b is d.c
- False
- >>> d = FlatDict(a=1, b="${a}", c="${b}")
- >>> d.dict()
- {'a': 1, 'b': '${a}', 'c': '${b}'}
- >>> d.interpolate(False).dict()
- {'a': 1, 'b': 1, 'c': 1}
- >>> isinstance(d.a, Variable)
- False
- >>> d.a += 1
- >>> d.dict()
- {'a': 2, 'b': 1, 'c': 1}
- >>> d = FlatDict(a=1, b="${b}", c="${b}")
- >>> d.interpolate().dict()
- Traceback (most recent call last):
- ValueError: Cannot interpolate b to itself.
- >>> d = FlatDict(a="${b}", b="${c}", c="${d}", d="${a}")
- >>> d.interpolate().dict()
- Traceback (most recent call last):
- ValueError: Circular reference found: a->b->c->d->a.
- >>> d = FlatDict(a=1, b="${a}", c="${d}")
- >>> d.interpolate().dict()
- Traceback (most recent call last):
- ValueError: d is not found in FlatDict(
- ('a'): '1'
- ('b'): '${a}'
- ('c'): '${d}'
- ).
- """
- # pylint: disable=C0103
-
- interpolators = interpolators or self
- placeholders : dict [ str , list [ str ]] = {}
- for key , value in self . all_items ():
- if isinstance ( value , list ):
- for v in value :
- self . find_placeholders ( key , v , placeholders )
- elif isinstance ( value , Mapping ):
- for v in value . values ():
- self . find_placeholders ( key , v , placeholders )
- else :
- self . find_placeholders ( key , value , placeholders )
- circular_references = find_circular_reference ( placeholders )
- if circular_references :
- raise ValueError ( f "Circular reference found: { '->' . join ( circular_references ) } ." )
- if use_variable :
- placeholder_names = { i for j in placeholders . values () for i in j }
- for name in list ( placeholder_names . difference ( placeholders . keys ())):
- if name not in interpolators :
- raise ValueError ( f " { name } is not found in { interpolators } ." )
- if not isinstance ( interpolators [ name ], Variable ):
- interpolators [ name ] = Variable ( interpolators [ name ])
- for key , value in placeholders . items ():
- if isinstance ( self [ key ], list ):
- for index , v in enumerate ( self [ key ]):
- self [ key ][ index ] = self . substitute ( v , interpolators , value )
- elif isinstance ( self [ key ], Mapping ):
- for k , v in self [ key ] . items ():
- self [ key ][ k ] = self . substitute ( v , interpolators , value )
- else :
- self [ key ] = self . substitute ( self [ key ], interpolators , value )
- if unsafe_eval and isinstance ( self [ key ], str ):
- with suppress ( SyntaxError ):
- self [ key ] = eval ( self [ key ]) # pylint: disable=W0123
- return self
-
- @staticmethod
- def find_placeholders ( key , value , placeholders ):
- placeholder = find_placeholders ( value )
- if placeholder :
- for index , name in enumerate ( placeholder ):
- if name . startswith ( "." ):
- placeholder [ index ] = key . rsplit ( "." , 1 )[ 0 ] + name
- if key == name :
- raise ValueError ( f "Cannot interpolate { key } to itself." )
- placeholders [ key ] = placeholder
-
- @staticmethod
- def substitute ( placeholder , interpolators , value ):
- try :
- if len ( value ) == 1 and placeholder . startswith ( "${" ) and placeholder . endswith ( "}" ):
- return interpolators [ value [ 0 ]]
- return placeholder . replace ( "$" , "" ) . format ( ** interpolators )
- except KeyError as exc :
- raise ValueError ( f " { exc } is not found in { interpolators } ." ) from None
-
- def merge ( self , * args : Any , overwrite : bool = True , ** kwargs : Any ) -> Self :
- r """
- Merge `other` into `FlatDict`.
-
- Args:
- *args: `Mapping` or `Sequence` to be merged.
- overwrite: Whether to overwrite existing values.
- **kwargs: `Mapping` to be merged.
-
- Returns:
- self:
-
- **Alias**:
-
- + `union`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
- >>> d.merge(n).dict()
- {'a': 1, 'b': 'b', 'c': 'c', 'd': 'd'}
- >>> l = [('c', 3), ('d', 4)]
- >>> d.merge(l).dict()
- {'a': 1, 'b': 'b', 'c': 3, 'd': 4}
- >>> FlatDict(a=1, b=1, c=1).union(FlatDict(b='b', c='c', d='d')).dict() # alias
- {'a': 1, 'b': 'b', 'c': 'c', 'd': 'd'}
- >>> d = FlatDict()
- >>> d.merge({1: 1, 2: 2, 3:3}).dict()
- {1: 1, 2: 2, 3: 3}
- >>> d.merge(d.clone()).dict()
- {1: 1, 2: 2, 3: 3}
- >>> d.merge({1:3, 2:1, 3: 2, 4: 4, 5: 5}, overwrite=False).dict()
- {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
- """
-
- if len ( args ) == 1 :
- args = args [ 0 ]
- if isinstance ( args , ( PathLike , str , bytes )):
- args = self . load ( args ) # type: ignore[assignment]
- warn (
- "merge file is deprecated and maybe removed in a future release. Use `merge_from_file` instead." ,
- PendingDeprecationWarning ,
- )
- self . _merge ( self , args , overwrite = overwrite )
- elif len ( args ) > 1 :
- self . _merge ( self , args , overwrite = overwrite )
- if kwargs :
- self . _merge ( self , kwargs , overwrite = overwrite )
- return self
-
- @staticmethod
- def _merge ( this : FlatDict , that : Iterable , overwrite : bool = True ) -> Mapping :
- if not that :
- return this
- if isinstance ( that , Mapping ):
- that = that . items ()
- for key , value in that :
- if key in this and isinstance ( this [ key ], Mapping ):
- if isinstance ( value , Mapping ):
- FlatDict . _merge ( this [ key ], value )
- elif overwrite :
- if isinstance ( value , FlatDict ):
- this . set ( key , value )
- else :
- this [ key ] = value
- elif overwrite or key not in this :
- this . set ( key , value )
- return this
-
- def union ( self , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Alias of [`merge`][chanfig.FlatDict.merge].
- """
- return self . merge ( * args , ** kwargs )
-
- def merge_from_file ( self , file : File , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Merge content of `file` into `FlatDict`.
-
- Args:
- file (File):
- *args: Passed to [`load`][chanfig.FlatDict.load].
- **kwargs: Passed to [`load`][chanfig.FlatDict.load].
-
- Returns:
- self:
-
- Examples:
- >>> d = FlatDict(a=1, b=1)
- >>> d.merge_from_file("tests/test.yaml").dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- return self . merge ( self . load ( file , * args , ** kwargs ))
-
- def intersect ( self , other : Mapping | Iterable | PathStr ) -> Self :
- r """
- Intersection of `FlatDict` and `other`.
-
- Args:
- other (Mapping | Iterable | PathStr):
+ items = sorted ( self . items (), key = key , reverse = reverse )
+ self . clear ()
+ for k , v in items : # pylint: disable=C0103
+ self [ k ] = v
+ return self
+
+ def interpolate ( # pylint: disable=R0912
+ self , use_variable : bool = True , interpolators : MutableMapping | None = None , unsafe_eval : bool = False
+ ) -> Self :
+ r """
+ Perform Variable interpolation.
+
+ Variable interpolation allows you to set the value of one key to be the value of another key easily.
+
+ Args:
+ use_variable: Whether to convert values to `Variable` objects.
+ interpolators: Mapping contains values for interpolation. Defaults to `self`.
+ unsafe_eval: Whether to evaluate interpolated values.
+
+ Raises:
+ ValueError: If value is not interpolatable.
+ ValueError: If reference to itself.
+ ValueError: If has circular reference.
+
+ See Also:
+ [Variable][`chanfig.Variable`]: Mutable wrapper of immutable objects.
+
+ Examples:
+ >>> d = FlatDict(a=1, b="${a}", c="${a}.${b}")
+ >>> d.dict()
+ {'a': 1, 'b': '${a}', 'c': '${a}.${b}'}
+ >>> d.interpolate(unsafe_eval=True).dict()
+ {'a': 1, 'b': 1, 'c': 1.1}
+ >>> d = FlatDict(a=1, b="${a}", c="${a}.${b}")
+ >>> d.dict()
+ {'a': 1, 'b': '${a}', 'c': '${a}.${b}'}
+ >>> d.interpolate().dict()
+ {'a': 1, 'b': 1, 'c': '1.1'}
+ >>> isinstance(d.a, Variable)
+ True
+ >>> d.a += 1
+ >>> d.dict()
+ {'a': 2, 'b': 2, 'c': '1.1'}
+ >>> d.a is d.b
+ True
+ >>> d.b is d.c
+ False
+ >>> d = FlatDict(a=1, b="${a}", c="${b}")
+ >>> d.dict()
+ {'a': 1, 'b': '${a}', 'c': '${b}'}
+ >>> d.interpolate(False).dict()
+ {'a': 1, 'b': 1, 'c': 1}
+ >>> isinstance(d.a, Variable)
+ False
+ >>> d.a += 1
+ >>> d.dict()
+ {'a': 2, 'b': 1, 'c': 1}
+ >>> d = FlatDict(a=1, b="${b}", c="${b}")
+ >>> d.interpolate().dict()
+ Traceback (most recent call last):
+ ValueError: Cannot interpolate b to itself.
+ >>> d = FlatDict(a="${b}", b="${c}", c="${d}", d="${a}")
+ >>> d.interpolate().dict()
+ Traceback (most recent call last):
+ ValueError: Circular reference found: a->b->c->d->a.
+ >>> d = FlatDict(a=1, b="${a}", c="${d}")
+ >>> d.interpolate().dict()
+ Traceback (most recent call last):
+ ValueError: d is not found in FlatDict(
+ ('a'): '1'
+ ('b'): '${a}'
+ ('c'): '${d}'
+ ).
+ """
+ # pylint: disable=C0103
+
+ interpolators = interpolators or self
+ placeholders : dict [ str , list [ str ]] = {}
+ for key , value in self . all_items ():
+ if isinstance ( value , list ):
+ for v in value :
+ self . find_placeholders ( key , v , placeholders )
+ elif isinstance ( value , Mapping ):
+ for v in value . values ():
+ self . find_placeholders ( key , v , placeholders )
+ else :
+ self . find_placeholders ( key , value , placeholders )
+ circular_references = find_circular_reference ( placeholders )
+ if circular_references :
+ raise ValueError ( f "Circular reference found: { '->' . join ( circular_references ) } ." )
+ if use_variable :
+ placeholder_names = { i for j in placeholders . values () for i in j }
+ for name in list ( placeholder_names . difference ( placeholders . keys ())):
+ if name not in interpolators :
+ raise ValueError ( f " { name } is not found in { interpolators } ." )
+ if not isinstance ( interpolators [ name ], Variable ):
+ interpolators [ name ] = Variable ( interpolators [ name ])
+ for key , value in placeholders . items ():
+ if isinstance ( self [ key ], list ):
+ for index , v in enumerate ( self [ key ]):
+ self [ key ][ index ] = self . substitute ( v , interpolators , value )
+ elif isinstance ( self [ key ], Mapping ):
+ for k , v in self [ key ] . items ():
+ self [ key ][ k ] = self . substitute ( v , interpolators , value )
+ else :
+ self [ key ] = self . substitute ( self [ key ], interpolators , value )
+ if unsafe_eval and isinstance ( self [ key ], str ):
+ with suppress ( SyntaxError ):
+ self [ key ] = eval ( self [ key ]) # pylint: disable=W0123
+ return self
+
+ @staticmethod
+ def find_placeholders ( key , value , placeholders ):
+ placeholder = find_placeholders ( value )
+ if placeholder :
+ for index , name in enumerate ( placeholder ):
+ if name . startswith ( "." ):
+ placeholder [ index ] = key . rsplit ( "." , 1 )[ 0 ] + name
+ if key == name :
+ raise ValueError ( f "Cannot interpolate { key } to itself." )
+ placeholders [ key ] = placeholder
+
+ @staticmethod
+ def substitute ( placeholder , interpolators , value ):
+ try :
+ if len ( value ) == 1 and placeholder . startswith ( "${" ) and placeholder . endswith ( "}" ):
+ return interpolators [ value [ 0 ]]
+ return placeholder . replace ( "$" , "" ) . format ( ** interpolators )
+ except KeyError as exc :
+ raise ValueError ( f " { exc } is not found in { interpolators } ." ) from None
+
+ def merge ( self , * args : Any , overwrite : bool = True , ** kwargs : Any ) -> Self :
+ r """
+ Merge `other` into `FlatDict`.
+
+ Args:
+ *args: `Mapping` or `Sequence` to be merged.
+ overwrite: Whether to overwrite existing values.
+ **kwargs: `Mapping` to be merged.
+
+ Returns:
+ self:
+
+ **Alias**:
+
+ + `union`
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> d.merge(n).dict()
+ {'a': 1, 'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> l = [('c', 3), ('d', 4)]
+ >>> d.merge(l).dict()
+ {'a': 1, 'b': 'b', 'c': 3, 'd': 4}
+ >>> FlatDict(a=1, b=1, c=1).union(FlatDict(b='b', c='c', d='d')).dict() # alias
+ {'a': 1, 'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> d = FlatDict()
+ >>> d.merge({1: 1, 2: 2, 3:3}).dict()
+ {1: 1, 2: 2, 3: 3}
+ >>> d.merge(d.clone()).dict()
+ {1: 1, 2: 2, 3: 3}
+ >>> d.merge({1:3, 2:1, 3: 2, 4: 4, 5: 5}, overwrite=False).dict()
+ {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
+ """
+
+ if len ( args ) == 1 :
+ args = args [ 0 ]
+ if isinstance ( args , ( PathLike , str , bytes )):
+ args = self . load ( args ) # type: ignore[assignment]
+ warn (
+ "merge file is deprecated and maybe removed in a future release. Use `merge_from_file` instead." ,
+ PendingDeprecationWarning ,
+ )
+ self . _merge ( self , args , overwrite = overwrite )
+ elif len ( args ) > 1 :
+ self . _merge ( self , args , overwrite = overwrite )
+ if kwargs :
+ self . _merge ( self , kwargs , overwrite = overwrite )
+ return self
+
+ @staticmethod
+ def _merge ( this : FlatDict , that : Iterable , overwrite : bool = True ) -> Mapping :
+ if not that :
+ return this
+ if isinstance ( that , Mapping ):
+ that = that . items ()
+ for key , value in that :
+ if key in this and isinstance ( this [ key ], Mapping ):
+ if isinstance ( value , Mapping ):
+ FlatDict . _merge ( this [ key ], value )
+ elif overwrite :
+ if isinstance ( value , FlatDict ):
+ this . set ( key , value )
+ else :
+ this [ key ] = value
+ elif overwrite or key not in this :
+ this . set ( key , value )
+ return this
+
+ def union ( self , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Alias of [`merge`][chanfig.FlatDict.merge].
+ """
+ return self . merge ( * args , ** kwargs )
- Returns:
- (FlatDict):
-
- **Alias**:
-
- + `inter`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
- >>> d.intersect(n).dict()
- {}
- >>> l = [('c', 3), ('d', 4)]
- >>> d.intersect(l).dict()
- {'c': 3}
- >>> d.merge(l).intersect("tests/test.yaml").dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> d.intersect(1)
- Traceback (most recent call last):
- TypeError: `other=1` should be of type Mapping, Iterable or PathStr, but got <class 'int'>.
- >>> d.inter(FlatDict(b='b', c='c', d='d')).dict() # alias
- {}
- """
+ def merge_from_file ( self , file : File , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Merge content of `file` into `FlatDict`.
+
+ Args:
+ file (File):
+ *args: Passed to [`load`][chanfig.FlatDict.load].
+ **kwargs: Passed to [`load`][chanfig.FlatDict.load].
+
+ Returns:
+ self:
+
+ Examples:
+ >>> d = FlatDict(a=1, b=1)
+ >>> d.merge_from_file("tests/test.yaml").dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ return self . merge ( self . load ( file , * args , ** kwargs ))
+
+ def intersect ( self , other : Mapping | Iterable | PathStr ) -> Self :
+ r """
+ Intersection of `FlatDict` and `other`.
- if isinstance ( other , ( PathLike , str , bytes )):
- other = self . load ( other )
- if isinstance ( other , ( Mapping ,)):
- other = self . empty ( other ) . items ()
- if not isinstance ( other , Iterable ):
- raise TypeError ( f "`other= { other } ` should be of type Mapping, Iterable or PathStr, but got { type ( other ) } ." )
- return self . empty ( ** { key : value for key , value in other if key in self and self [ key ] == value }) # type: ignore
+ Args:
+ other (Mapping | Iterable | PathStr):
+
+ Returns:
+ (FlatDict):
+
+ **Alias**:
- def inter ( self , other : Mapping | Iterable | PathStr , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Alias of [`intersect`][chanfig.FlatDict.intersect].
- """
- return self . intersect ( other , * args , ** kwargs )
-
- def difference ( self , other : Mapping | Iterable | PathStr ) -> Self :
- r """
- Difference between `FlatDict` and `other`.
-
- Args:
- other:
-
- Returns:
- (FlatDict):
-
- **Alias**:
-
- + `diff`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
- >>> d.difference(n).dict()
- {'b': 'b', 'c': 'c', 'd': 'd'}
- >>> l = [('c', 3), ('d', 4)]
- >>> d.difference(l).dict()
- {'d': 4}
- >>> d.merge(l).difference("tests/test.yaml").dict()
- {}
- >>> d.difference(1)
- Traceback (most recent call last):
- TypeError: `other=1` should be of type Mapping, Iterable or PathStr, but got <class 'int'>.
- >>> FlatDict(a=1, b=1, c=1).diff(FlatDict(b='b', c='c', d='d')).dict() # alias
- {'b': 'b', 'c': 'c', 'd': 'd'}
- """
+ + `inter`
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> d.intersect(n).dict()
+ {}
+ >>> l = [('c', 3), ('d', 4)]
+ >>> d.intersect(l).dict()
+ {'c': 3}
+ >>> d.merge(l).intersect("tests/test.yaml").dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> d.intersect(1)
+ Traceback (most recent call last):
+ TypeError: `other=1` should be of type Mapping, Iterable or PathStr, but got <class 'int'>.
+ >>> d.inter(FlatDict(b='b', c='c', d='d')).dict() # alias
+ {}
+ """
+
+ if isinstance ( other , ( PathLike , str , bytes )):
+ other = self . load ( other )
+ if isinstance ( other , ( Mapping ,)):
+ other = self . empty ( other ) . items ()
+ if not isinstance ( other , Iterable ):
+ raise TypeError ( f "`other= { other } ` should be of type Mapping, Iterable or PathStr, but got { type ( other ) } ." )
+ return self . empty ( ** { key : value for key , value in other if key in self and self [ key ] == value }) # type: ignore
+
+ def inter ( self , other : Mapping | Iterable | PathStr , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Alias of [`intersect`][chanfig.FlatDict.intersect].
+ """
+ return self . intersect ( other , * args , ** kwargs )
+
+ def difference ( self , other : Mapping | Iterable | PathStr ) -> Self :
+ r """
+ Difference between `FlatDict` and `other`.
- if isinstance ( other , ( PathLike , str , bytes )):
- other = self . load ( other )
- if isinstance ( other , ( Mapping ,)):
- other = self . empty ( other ) . items ()
- if not isinstance ( other , Iterable ):
- raise TypeError ( f "`other= { other } ` should be of type Mapping, Iterable or PathStr, but got { type ( other ) } ." )
- return self . empty (
- ** { key : value for key , value in other if key not in self or self [ key ] != value } # type: ignore[misc]
- )
+ Args:
+ other:
+
+ Returns:
+ (FlatDict):
+
+ **Alias**:
+
+ + `diff`
- def diff ( self , other : Mapping | Iterable | PathStr , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Alias of [`difference`][chanfig.FlatDict.difference].
- """
- return self . difference ( other , * args , ** kwargs )
-
- def to ( self , cls : str | TorchDevice | TorchDType ) -> Self : # pragma: no cover
- r """
- Convert values of `FlatDict` to target `cls`.
-
- Args:
- cls (str | torch.device | torch.dtype):
-
- Returns:
- self:
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.to(int)
- Traceback (most recent call last):
- TypeError: to() only support torch.dtype and torch.device, but got <class 'int'>.
- """
-
- # pylint: disable=C0103
-
- if isinstance ( cls , ( str , TorchDevice , TorchDType )):
- for k , v in self . all_items ():
- if hasattr ( v , "to" ):
- self [ k ] = v . to ( cls )
- return self
-
- raise TypeError ( f "to() only support torch.dtype and torch.device, but got { cls } ." )
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> d.difference(n).dict()
+ {'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> l = [('c', 3), ('d', 4)]
+ >>> d.difference(l).dict()
+ {'d': 4}
+ >>> d.merge(l).difference("tests/test.yaml").dict()
+ {}
+ >>> d.difference(1)
+ Traceback (most recent call last):
+ TypeError: `other=1` should be of type Mapping, Iterable or PathStr, but got <class 'int'>.
+ >>> FlatDict(a=1, b=1, c=1).diff(FlatDict(b='b', c='c', d='d')).dict() # alias
+ {'b': 'b', 'c': 'c', 'd': 'd'}
+ """
+
+ if isinstance ( other , ( PathLike , str , bytes )):
+ other = self . load ( other )
+ if isinstance ( other , ( Mapping ,)):
+ other = self . empty ( other ) . items ()
+ if not isinstance ( other , Iterable ):
+ raise TypeError ( f "`other= { other } ` should be of type Mapping, Iterable or PathStr, but got { type ( other ) } ." )
+ return self . empty (
+ ** { key : value for key , value in other if key not in self or self [ key ] != value } # type: ignore[misc]
+ )
+
+ def diff ( self , other : Mapping | Iterable | PathStr , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Alias of [`difference`][chanfig.FlatDict.difference].
+ """
+ return self . difference ( other , * args , ** kwargs )
- def cpu ( self ) -> Self : # pragma: no cover
+ def to ( self , cls : str | TorchDevice | TorchDType ) -> Self : # pragma: no cover
r """
- Move all tensors to cpu.
+ Convert values of `FlatDict` to target `cls`.
- Returns:
- self:
+ Args:
+ cls (str | torch.device | torch.dtype):
- Examples:
- >>> import torch
- >>> d = FlatDict(a=torch.tensor(1))
- >>> d.cpu().dict() # doctest: +SKIP
- {'a': tensor(1, device='cpu')}
- """
-
- return self . to ( TorchDevice ( "cpu" ))
-
- def gpu ( self ) -> Self : # pragma: no cover
- r """
- Move all tensors to gpu.
-
- Returns:
- self:
-
- **Alias**:
+ Returns:
+ self:
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.to(int)
+ Traceback (most recent call last):
+ TypeError: to() only support torch.dtype and torch.device, but got <class 'int'>.
+ """
+
+ # pylint: disable=C0103
+
+ if isinstance ( cls , ( str , TorchDevice , TorchDType )):
+ for k , v in self . all_items ():
+ if hasattr ( v , "to" ):
+ self [ k ] = v . to ( cls )
+ return self
- + `cuda`
+ raise TypeError ( f "to() only support torch.dtype and torch.device, but got { cls } ." )
- Examples:
- >>> import torch
- >>> d = FlatDict(a=torch.tensor(1))
- >>> d.gpu().dict() # doctest: +SKIP
- {'a': tensor(1, device='cuda:0')}
- >>> d.cuda().dict() # alias # doctest: +SKIP
- {'a': tensor(1, device='cuda:0')}
- """
-
- return self . to ( TorchDevice ( "cuda" ))
-
- def cuda ( self ) -> Self : # pragma: no cover
- r """
- Alias of [`gpu`][chanfig.FlatDict.gpu].
- """
- return self . gpu ()
-
- def tpu ( self ) -> Self : # pragma: no cover
- r """
- Move all tensors to tpu.
-
- Returns:
- self:
-
- **Alias**:
-
- + `xla`
-
- Examples:
- >>> import torch
- >>> d = FlatDict(a=torch.tensor(1))
- >>> d.tpu().dict() # doctest: +SKIP
- {'a': tensor(1, device='xla:0')}
- >>> d.xla().dict() # alias # doctest: +SKIP
- {'a': tensor(1, device='xla:0')}
- """
-
- return self . to ( TorchDevice ( "xla" ))
-
- def xla ( self ) -> Self : # pragma: no cover
- r """
- Alias of [`tpu`][chanfig.FlatDict.tpu].
- """
- return self . tpu ()
-
- def copy ( self ) -> Self :
- r """
- Create a shallow copy of `FlatDict`.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> d.setattr("name", "Chang")
- >>> c = d.copy()
- >>> c.dict()
- {'a': []}
- >>> d.a.append(1)
- >>> c.dict()
- {'a': [1]}
- >>> c.getattr("name")
- 'Chang'
- """
-
- return copy ( self )
-
- def __deepcopy__ ( self , memo : Mapping | None = None ) -> Self :
- # pylint: disable=C0103
-
- if memo is not None and id ( self ) in memo :
- return memo [ id ( self )]
- ret = self . empty ()
- ret . __dict__ . update ( deepcopy ( self . __dict__ ))
- for k , v in self . items ():
- if isinstance ( v , FlatDict ):
- ret [ k ] = v . deepcopy ( memo = memo )
- else :
- ret [ k ] = deepcopy ( v )
- return ret
-
- def deepcopy ( self , memo : Mapping | None = None ) -> Self : # pylint: disable=W0613
- r """
- Create a deep copy of `FlatDict`.
-
- Returns:
- (FlatDict):
-
- **Alias**:
-
- + `clone`
+ def cpu ( self ) -> Self : # pragma: no cover
+ r """
+ Move all tensors to cpu.
+
+ Returns:
+ self:
+
+ Examples:
+ >>> import torch
+ >>> d = FlatDict(a=torch.tensor(1))
+ >>> d.cpu().dict() # doctest: +SKIP
+ {'a': tensor(1, device='cpu')}
+ """
+
+ return self . to ( TorchDevice ( "cpu" ))
+
+ def gpu ( self ) -> Self : # pragma: no cover
+ r """
+ Move all tensors to gpu.
+
+ Returns:
+ self:
+
+ **Alias**:
+
+ + `cuda`
+
+ Examples:
+ >>> import torch
+ >>> d = FlatDict(a=torch.tensor(1))
+ >>> d.gpu().dict() # doctest: +SKIP
+ {'a': tensor(1, device='cuda:0')}
+ >>> d.cuda().dict() # alias # doctest: +SKIP
+ {'a': tensor(1, device='cuda:0')}
+ """
+
+ return self . to ( TorchDevice ( "cuda" ))
+
+ def cuda ( self ) -> Self : # pragma: no cover
+ r """
+ Alias of [`gpu`][chanfig.FlatDict.gpu].
+ """
+ return self . gpu ()
+
+ def tpu ( self ) -> Self : # pragma: no cover
+ r """
+ Move all tensors to tpu.
+
+ Returns:
+ self:
+
+ **Alias**:
+
+ + `xla`
+
+ Examples:
+ >>> import torch
+ >>> d = FlatDict(a=torch.tensor(1))
+ >>> d.tpu().dict() # doctest: +SKIP
+ {'a': tensor(1, device='xla:0')}
+ >>> d.xla().dict() # alias # doctest: +SKIP
+ {'a': tensor(1, device='xla:0')}
+ """
+
+ return self . to ( TorchDevice ( "xla" ))
+
+ def xla ( self ) -> Self : # pragma: no cover
+ r """
+ Alias of [`tpu`][chanfig.FlatDict.tpu].
+ """
+ return self . tpu ()
+
+ def copy ( self ) -> Self :
+ r """
+ Create a shallow copy of `FlatDict`.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> d.setattr("name", "Chang")
+ >>> c = d.copy()
+ >>> c.dict()
+ {'a': []}
+ >>> d.a.append(1)
+ >>> c.dict()
+ {'a': [1]}
+ >>> c.getattr("name")
+ 'Chang'
+ """
- Examples:
- >>> d = FlatDict(a=[])
- >>> d.setattr("name", "Chang")
- >>> c = d.deepcopy()
- >>> c.dict()
- {'a': []}
- >>> d.a.append(1)
- >>> c.dict()
- {'a': []}
- >>> c.getattr("name")
- 'Chang'
- >>> d == d.clone() # alias
- True
- """
-
- return deepcopy ( self )
-
- def clone ( self , memo : Mapping | None = None ) -> Self :
- r """
- Alias of [`deepcopy`][chanfig.FlatDict.deepcopy].
- """
- return self . deepcopy ( memo = memo )
+ return copy ( self )
+
+ def __deepcopy__ ( self , memo : Mapping | None = None ) -> Self :
+ # pylint: disable=C0103
+
+ if memo is not None and id ( self ) in memo :
+ return memo [ id ( self )]
+ ret = self . empty ()
+ ret . __dict__ . update ( deepcopy ( self . __dict__ ))
+ for k , v in self . items ():
+ if isinstance ( v , FlatDict ):
+ ret [ k ] = v . deepcopy ( memo = memo )
+ else :
+ ret [ k ] = deepcopy ( v )
+ return ret
+
+ def deepcopy ( self , memo : Mapping | None = None ) -> Self : # pylint: disable=W0613
+ r """
+ Create a deep copy of `FlatDict`.
+
+ Returns:
+ (FlatDict):
- def save ( # pylint: disable=W1113
- self , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
- ) -> None :
- r """
- Save `FlatDict` to file.
-
- Raises:
- ValueError: If save to `IO` and `method` is not specified.
- TypeError: If save to unsupported extension.
-
- **Alias**:
-
- + `save`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.save("tests/test.yaml")
- >>> d.save("test.conf")
- Traceback (most recent call last):
- TypeError: `file='test.conf'` should be in ('json',) or ('yml', 'yaml'), but got conf.
- >>> with open("test.yaml", "w") as f:
- ... d.save(f)
- Traceback (most recent call last):
- ValueError: `method` must be specified when saving to IO.
+ **Alias**:
+
+ + `clone`
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> d.setattr("name", "Chang")
+ >>> c = d.deepcopy()
+ >>> c.dict()
+ {'a': []}
+ >>> d.a.append(1)
+ >>> c.dict()
+ {'a': []}
+ >>> c.getattr("name")
+ 'Chang'
+ >>> d == d.clone() # alias
+ True
+ """
+
+ return deepcopy ( self )
+
+ def clone ( self , memo : Mapping | None = None ) -> Self :
+ r """
+ Alias of [`deepcopy`][chanfig.FlatDict.deepcopy].
"""
-
- if method is None :
- if isinstance ( file , ( IOBase , IO )):
- raise ValueError ( "`method` must be specified when saving to IO." )
- method = splitext ( file )[ - 1 ][ 1 :]
- extension = method . lower ()
- if extension in YAML :
- return self . yaml ( file = file , * args , ** kwargs ) # type: ignore[misc] # noqa: B026
- if extension in JSON :
- return self . json ( file = file , * args , ** kwargs ) # type: ignore[misc] # noqa: B026
- raise TypeError ( f "`file= { file !r} ` should be in { JSON } or { YAML } , but got { extension } ." )
+ return self . deepcopy ( memo = memo )
+
+ def save ( # pylint: disable=W1113
+ self , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
+ ) -> None :
+ r """
+ Save `FlatDict` to file.
+
+ Raises:
+ ValueError: If save to `IO` and `method` is not specified.
+ TypeError: If save to unsupported extension.
- def dump ( # pylint: disable=W1113
- self , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
- ) -> None :
- r """
- Alias of [`save`][chanfig.FlatDict.save].
- """
- return self . save ( file , method , * args , ** kwargs )
-
- @classmethod
- def load ( # pylint: disable=W1113
- cls , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
- ) -> Self :
- """
- Load `FlatDict` from file.
-
- Args:
- file: File to load from.
- method: File type, should be in `JSON` or `YAML`.
-
- Returns:
- (FlatDict):
-
- Raises:
- ValueError: If load from `IO` and `method` is not specified.
- TypeError: If dump to unsupported extension.
-
- Examples:
- >>> d = FlatDict.load("tests/test.yaml")
- >>> d.dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> d.load("tests/test.conf")
- Traceback (most recent call last):
- TypeError: `file='tests/test.conf'` should be in ('json',) or ('yml', 'yaml'), but got conf.
- >>> with open("tests/test.yaml") as f:
- ... d.load(f)
- Traceback (most recent call last):
- ValueError: `method` must be specified when loading from IO.
- """
-
- if method is None :
- if isinstance ( file , ( IOBase , IO )):
- raise ValueError ( "`method` must be specified when loading from IO." )
- method = splitext ( file )[ - 1 ][ 1 :]
- extension = method . lower ()
- if extension in JSON :
- return cls . from_json ( file , * args , ** kwargs )
- if extension in YAML :
- return cls . from_yaml ( file , * args , ** kwargs )
- raise TypeError ( f "`file= { file !r} ` should be in { JSON } or { YAML } , but got { extension } ." )
-
- def json ( self , file : File , * args : Any , ** kwargs : Any ) -> None :
- r """
- Dump `FlatDict` to json file.
-
- This method internally calls `self.jsons()` to generate json string.
- You may overwrite `jsons` in case something is not json serializable.
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.json("tests/test.json")
- """
-
- with self . open ( file , mode = "w" ) as fp : # pylint: disable=C0103
- fp . write ( self . jsons ( * args , ** kwargs ))
-
- @classmethod
- def from_json ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from json file.
-
- This method internally calls `self.from_jsons()` to construct object from json string.
- You may overwrite `from_jsons` in case something is not json serializable.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> d = FlatDict.from_json('tests/test.json')
- >>> d.dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- with cls . open ( file ) as fp : # pylint: disable=C0103
- if isinstance ( file , ( IOBase , IO )):
- return cls . from_jsons ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
- return cls . from_jsons ( fp . read (), * args , ** kwargs )
-
- def jsons ( self , * args : Any , ** kwargs : Any ) -> str :
- r """
- Dump `FlatDict` to json string.
-
- Returns:
- (str):
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.jsons()
- '{\n "a": 1,\n "b": 2,\n "c": 3\n}'
- """
+ **Alias**:
+
+ + `save`
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.save("tests/test.yaml")
+ >>> d.save("test.conf")
+ Traceback (most recent call last):
+ TypeError: `file='test.conf'` should be in ('json',) or ('yml', 'yaml'), but got conf.
+ >>> with open("test.yaml", "w") as f:
+ ... d.save(f)
+ Traceback (most recent call last):
+ ValueError: `method` must be specified when saving to IO.
+ """
+
+ if method is None :
+ if isinstance ( file , ( IOBase , IO )):
+ raise ValueError ( "`method` must be specified when saving to IO." )
+ method = splitext ( file )[ - 1 ][ 1 :]
+ extension = method . lower ()
+ if extension in YAML :
+ return self . yaml ( file = file , * args , ** kwargs ) # type: ignore[misc] # noqa: B026
+ if extension in JSON :
+ return self . json ( file = file , * args , ** kwargs ) # type: ignore[misc] # noqa: B026
+ raise TypeError ( f "`file= { file !r} ` should be in { JSON } or { YAML } , but got { extension } ." )
+
+ def dump ( # pylint: disable=W1113
+ self , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
+ ) -> None :
+ r """
+ Alias of [`save`][chanfig.FlatDict.save].
+ """
+ return self . save ( file , method , * args , ** kwargs )
+
+ @classmethod
+ def load ( # pylint: disable=W1113
+ cls , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
+ ) -> Self :
+ """
+ Load `FlatDict` from file.
+
+ Args:
+ file: File to load from.
+ method: File type, should be in `JSON` or `YAML`.
+
+ Returns:
+ (FlatDict):
+
+ Raises:
+ ValueError: If load from `IO` and `method` is not specified.
+ TypeError: If dump to unsupported extension.
+
+ Examples:
+ >>> d = FlatDict.load("tests/test.yaml")
+ >>> d.dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> d.load("tests/test.conf")
+ Traceback (most recent call last):
+ TypeError: `file='tests/test.conf'` should be in ('json',) or ('yml', 'yaml'), but got conf.
+ >>> with open("tests/test.yaml") as f:
+ ... d.load(f)
+ Traceback (most recent call last):
+ ValueError: `method` must be specified when loading from IO.
+ """
+
+ if method is None :
+ if isinstance ( file , ( IOBase , IO )):
+ raise ValueError ( "`method` must be specified when loading from IO." )
+ method = splitext ( file )[ - 1 ][ 1 :]
+ extension = method . lower ()
+ if extension in JSON :
+ return cls . from_json ( file , * args , ** kwargs )
+ if extension in YAML :
+ return cls . from_yaml ( file , * args , ** kwargs )
+ raise TypeError ( f "`file= { file !r} ` should be in { JSON } or { YAML } , but got { extension } ." )
+
+ def json ( self , file : File , * args : Any , ** kwargs : Any ) -> None :
+ r """
+ Dump `FlatDict` to json file.
+
+ This method internally calls `self.jsons()` to generate json string.
+ You may overwrite `jsons` in case something is not json serializable.
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.json("tests/test.json")
+ """
+
+ with self . open ( file , mode = "w" ) as fp : # pylint: disable=C0103
+ fp . write ( self . jsons ( * args , ** kwargs ))
+
+ @classmethod
+ def from_json ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from json file.
+
+ This method internally calls `self.from_jsons()` to construct object from json string.
+ You may overwrite `from_jsons` in case something is not json serializable.
- kwargs . setdefault ( "cls" , JsonEncoder )
- kwargs . setdefault ( "indent" , self . getattr ( "indent" , 2 ))
- return json_dumps ( self . dict (), * args , ** kwargs )
-
- @classmethod
- def from_jsons ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from json string.
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> d = FlatDict.from_json('tests/test.json')
+ >>> d.dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
- Returns:
- (FlatDict):
-
- Examples:
- >>> FlatDict.from_jsons('{\n "a": 1,\n "b": 2,\n "c": 3\n}').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_jsons('[["a", 1], ["b", 2], ["c", 3]]').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_jsons('[{"a": 1}, {"b": 2}, {"c": 3}]')
- [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
- """
+ with cls . open ( file ) as fp : # pylint: disable=C0103
+ if isinstance ( file , ( IOBase , IO )):
+ return cls . from_jsons ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
+ return cls . from_jsons ( fp . read (), * args , ** kwargs )
+
+ def jsons ( self , * args : Any , ** kwargs : Any ) -> str :
+ r """
+ Dump `FlatDict` to json string.
+
+ Returns:
+ (str):
- return cls . from_dict ( json_loads ( string , * args , ** kwargs ))
-
- def yaml ( self , file : File , * args : Any , ** kwargs : Any ) -> None :
- r """
- Dump `FlatDict` to yaml file.
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.jsons()
+ '{\n "a": 1,\n "b": 2,\n "c": 3\n}'
+ """
- This method internally calls `self.yamls()` to generate yaml string.
- You may overwrite `yamls` in case something is not yaml serializable.
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.yaml("tests/test.yaml")
- """
-
- with self . open ( file , mode = "w" ) as fp : # pylint: disable=C0103
- self . yamls ( fp , * args , ** kwargs )
-
- @classmethod
- def from_yaml ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from yaml file.
-
- This method internally calls `self.from_yamls()` to construct object from yaml string.
- You may overwrite `from_yamls` in case something is not yaml serializable.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> FlatDict.from_yaml('tests/test.yaml').dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
+ kwargs . setdefault ( "cls" , JsonEncoder )
+ kwargs . setdefault ( "indent" , self . getattr ( "indent" , 2 ))
+ return json_dumps ( self . dict (), * args , ** kwargs )
+
+ @classmethod
+ def from_jsons ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from json string.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> FlatDict.from_jsons('{\n "a": 1,\n "b": 2,\n "c": 3\n}').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_jsons('[["a", 1], ["b", 2], ["c", 3]]').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_jsons('[{"a": 1}, {"b": 2}, {"c": 3}]')
+ [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
+ """
+
+ return cls . from_dict ( json_loads ( string , * args , ** kwargs ))
+
+ def yaml ( self , file : File , * args : Any , ** kwargs : Any ) -> None :
+ r """
+ Dump `FlatDict` to yaml file.
- kwargs . setdefault ( "Loader" , YamlLoader )
- with cls . open ( file ) as fp : # pylint: disable=C0103
- if isinstance ( file , ( IOBase , IO )):
- return cls . from_yamls ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
- return cls . from_dict ( yaml_load ( fp , * args , ** kwargs ))
-
- def yamls ( self , * args : Any , ** kwargs : Any ) -> str :
- r """
- Dump `FlatDict` to yaml string.
-
- Returns:
- (str):
-
- Examples:
- >>> FlatDict(a=1, b=2, c=3).yamls()
- 'a: 1\nb: 2\nc: 3\n'
- """
-
- kwargs . setdefault ( "Dumper" , YamlDumper )
- kwargs . setdefault ( "indent" , self . getattr ( "indent" , 2 ))
- return yaml_dump ( self . dict (), * args , ** kwargs )
+ This method internally calls `self.yamls()` to generate yaml string.
+ You may overwrite `yamls` in case something is not yaml serializable.
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.yaml("tests/test.yaml")
+ """
+
+ with self . open ( file , mode = "w" ) as fp : # pylint: disable=C0103
+ self . yamls ( fp , * args , ** kwargs )
+
+ @classmethod
+ def from_yaml ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from yaml file.
+
+ This method internally calls `self.from_yamls()` to construct object from yaml string.
+ You may overwrite `from_yamls` in case something is not yaml serializable.
+
+ Returns:
+ (FlatDict):
- @classmethod
- def from_yamls ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from yaml string.
+ Examples:
+ >>> FlatDict.from_yaml('tests/test.yaml').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
- Returns:
- (FlatDict):
-
- Examples:
- >>> FlatDict.from_yamls('a: 1\nb: 2\nc: 3\n').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_yamls('- - a\n - 1\n- - b\n - 2\n- - c\n - 3\n').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_yamls('- a: 1\n- b: 2\n- c: 3\n')
- [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
- """
-
- kwargs . setdefault ( "Loader" , SafeLoader )
- return cls . from_dict ( yaml_load ( string , * args , ** kwargs ))
-
- @staticmethod
- @contextmanager
- def open ( file : File , * args : Any , encoding : str = "utf-8" , ** kwargs : Any ) -> Generator [ IOBase | IO , Any , Any ]:
- r """
- Open file IO from file path or IO.
-
- This methods extends the ability of built-in `open` by allowing it to accept an `IOBase` object.
-
- Args:
- file: File path or IO.
- *args: Additional arguments passed to `open`.
- Defaults to ().
- **kwargs: Any
- Additional keyword arguments passed to `open`.
- Defaults to {}.
-
- Yields:
- (Generator[IOBase | IO, Any, Any]):
-
- Examples:
- >>> with FlatDict.open("tests/test.yaml") as fp:
- ... print(fp.read())
- a: 1
- b: 2
- c: 3
- <BLANKLINE>
- >>> io = open("tests/test.yaml")
- >>> with FlatDict.open(io) as fp:
- ... print(fp.read())
- a: 1
- b: 2
- c: 3
- <BLANKLINE>
- >>> with FlatDict.open(123, mode="w") as fp:
- ... print(fp.read())
- Traceback (most recent call last):
- TypeError: expected str, bytes, os.PathLike, IO or IOBase, not int
- """
-
- if isinstance ( file , ( IOBase , IO )):
- yield file
- elif isinstance ( file , ( PathLike , str , bytes )):
- try :
- file = open ( file , * args , encoding = encoding , ** kwargs ) # type: ignore[call-overload] # noqa: SIM115
- yield file # type: ignore[misc]
- finally :
- with suppress ( Exception ):
- file . close () # type: ignore[union-attr]
- else :
- raise TypeError ( f "expected str, bytes, os.PathLike, IO or IOBase, not { type ( file ) . __name__ } " )
-
- @classmethod
- def empty ( cls , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Initialise an empty `FlatDict`.
-
- This method is helpful when you inheriting `FlatDict` with default values defined in `__init__()`.
- As use `type(self)()` in this case would copy all the default values, which might not be desired.
-
- This method will preserve everything in `FlatDict.__class__.__dict__`.
-
- Returns:
- (FlatDict):
-
- See Also:
- [`empty_like`][chanfig.FlatDict.empty_like]
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> c = d.empty()
- >>> c.dict()
- {}
- """
-
- empty = cls . __new__ ( cls )
- empty . merge ( * args , ** kwargs ) # pylint: disable=W0212
- return empty
+ kwargs . setdefault ( "Loader" , YamlLoader )
+ with cls . open ( file ) as fp : # pylint: disable=C0103
+ if isinstance ( file , ( IOBase , IO )):
+ return cls . from_yamls ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
+ return cls . from_dict ( yaml_load ( fp , * args , ** kwargs ))
+
+ def yamls ( self , * args : Any , ** kwargs : Any ) -> str :
+ r """
+ Dump `FlatDict` to yaml string.
+
+ Returns:
+ (str):
+
+ Examples:
+ >>> FlatDict(a=1, b=2, c=3).yamls()
+ 'a: 1\nb: 2\nc: 3\n'
+ """
+
+ kwargs . setdefault ( "Dumper" , YamlDumper )
+ kwargs . setdefault ( "indent" , self . getattr ( "indent" , 2 ))
+ return yaml_dump ( self . dict (), * args , ** kwargs )
+
+ @classmethod
+ def from_yamls ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from yaml string.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> FlatDict.from_yamls('a: 1\nb: 2\nc: 3\n').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_yamls('- - a\n - 1\n- - b\n - 2\n- - c\n - 3\n').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_yamls('- a: 1\n- b: 2\n- c: 3\n')
+ [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
+ """
+
+ kwargs . setdefault ( "Loader" , SafeLoader )
+ return cls . from_dict ( yaml_load ( string , * args , ** kwargs ))
+
+ @staticmethod
+ @contextmanager
+ def open ( file : File , * args : Any , encoding : str = "utf-8" , ** kwargs : Any ) -> Generator [ IOBase | IO , Any , Any ]:
+ r """
+ Open file IO from file path or IO.
+
+ This methods extends the ability of built-in `open` by allowing it to accept an `IOBase` object.
+
+ Args:
+ file: File path or IO.
+ *args: Additional arguments passed to `open`.
+ Defaults to ().
+ **kwargs: Any
+ Additional keyword arguments passed to `open`.
+ Defaults to {}.
+
+ Yields:
+ (Generator[IOBase | IO, Any, Any]):
+
+ Examples:
+ >>> with FlatDict.open("tests/test.yaml") as fp:
+ ... print(fp.read())
+ a: 1
+ b: 2
+ c: 3
+ <BLANKLINE>
+ >>> io = open("tests/test.yaml")
+ >>> with FlatDict.open(io) as fp:
+ ... print(fp.read())
+ a: 1
+ b: 2
+ c: 3
+ <BLANKLINE>
+ >>> with FlatDict.open(123, mode="w") as fp:
+ ... print(fp.read())
+ Traceback (most recent call last):
+ TypeError: expected str, bytes, os.PathLike, IO or IOBase, not int
+ """
+
+ if isinstance ( file , ( IOBase , IO )):
+ yield file
+ elif isinstance ( file , ( PathLike , str , bytes )):
+ try :
+ file = open ( file , * args , encoding = encoding , ** kwargs ) # type: ignore[call-overload] # noqa: SIM115
+ yield file # type: ignore[misc]
+ finally :
+ with suppress ( Exception ):
+ file . close () # type: ignore[union-attr]
+ else :
+ raise TypeError ( f "expected str, bytes, os.PathLike, IO or IOBase, not { type ( file ) . __name__ } " )
- def empty_like ( self , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Initialise an empty copy of `FlatDict`.
-
- This method will preserve everything in `FlatDict.__class__.__dict__` and `FlatDict.__dict__`.
-
- For example, `property`s are saved in `__dict__`, they will keep their original reference after calling this
- method.
-
- Returns:
- (FlatDict):
-
- See Also:
- [`empty`][chanfig.FlatDict.empty]
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> d.setattr("name", "Chang")
- >>> c = d.empty_like()
+ @classmethod
+ def empty ( cls , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Initialise an empty `FlatDict`.
+
+ This method is helpful when you inheriting `FlatDict` with default values defined in `__init__()`.
+ As use `type(self)()` in this case would copy all the default values, which might not be desired.
+
+ This method will preserve everything in `FlatDict.__class__.__dict__`.
+
+ Returns:
+ (FlatDict):
+
+ See Also:
+ [`empty_like`][chanfig.FlatDict.empty_like]
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> c = d.empty()
>>> c.dict()
{}
- >>> c.getattr("name")
- 'Chang'
- """
-
- empty = self . empty ( * args , ** kwargs )
- empty . __dict__ . update ( self . __dict__ )
- return empty
-
- def all_keys ( self ) -> Generator :
- r """
- Equivalent to `keys`.
+ """
+
+ empty = cls . __new__ ( cls )
+ empty . merge ( * args , ** kwargs ) # pylint: disable=W0212
+ return empty
+
+ def empty_like ( self , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Initialise an empty copy of `FlatDict`.
+
+ This method will preserve everything in `FlatDict.__class__.__dict__` and `FlatDict.__dict__`.
- This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
-
- See Also:
- [`all_keys`][chanfig.NestedDict.all_keys]
- """
- yield from self . keys ()
-
- def all_values ( self ) -> Generator :
- r """
- Equivalent to `keys`.
-
- This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
-
- See Also:
- [`all_values`][chanfig.NestedDict.all_values]
- """
- yield from self . values ()
-
- def all_items ( self ) -> Generator :
- r """
- Equivalent to `keys`.
-
- This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
-
- See Also:
- [`all_items`][chanfig.NestedDict.all_items]
- """
- yield from self . items ()
+ For example, `property`s are saved in `__dict__`, they will keep their original reference after calling this
+ method.
+
+ Returns:
+ (FlatDict):
+
+ See Also:
+ [`empty`][chanfig.FlatDict.empty]
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> d.setattr("name", "Chang")
+ >>> c = d.empty_like()
+ >>> c.dict()
+ {}
+ >>> c.getattr("name")
+ 'Chang'
+ """
+
+ empty = self . empty ( * args , ** kwargs )
+ empty . __dict__ . update ( self . __dict__ )
+ return empty
+
+ def all_keys ( self ) -> Generator :
+ r """
+ Equivalent to `keys`.
+
+ This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
- def dropnull ( self ) -> Self :
- r """
- Drop key-value pairs with `Null` value.
-
- Returns:
- (FlatDict):
-
- **Alias**:
+ See Also:
+ [`all_keys`][chanfig.NestedDict.all_keys]
+ """
+ yield from self . keys ()
+
+ def all_values ( self ) -> Generator :
+ r """
+ Equivalent to `keys`.
- + `dropna`
+ This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
- Examples:
- >>> d = FlatDict(a=Null, b=Null, c=3)
- >>> d.dict()
- {'a': Null, 'b': Null, 'c': 3}
- >>> d.dropnull().dict()
- {'c': 3}
- >>> d.dropna().dict() # alias
- {'c': 3}
- """
-
- return self . empty ({ k : v for k , v in self . all_items () if v is not Null })
-
- def dropna ( self ) -> Self :
- r """
- Alias of [`dropnull`][chanfig.FlatDict.dropnull].
- """
- return self . dropnull ()
-
- @staticmethod
- def extra_repr () -> str : # pylint: disable=C0116
- return ""
-
- def __repr__ ( self ) -> str :
- extra_lines = []
- extra_repr = self . extra_repr ()
- # empty string will be split into list ['']
- if extra_repr :
- extra_lines = extra_repr . split ( " \n " )
- child_lines = []
- for key , value in self . items ():
- key_repr = repr ( key )
- value_repr = repr ( value )
- value_repr = self . _add_indent ( value_repr )
- child_lines . append ( f "( { key_repr } ): { value_repr } " )
- # child_lines.append(f"{key_repr}: {value_repr}")
- lines = extra_lines + child_lines
+ See Also:
+ [`all_values`][chanfig.NestedDict.all_values]
+ """
+ yield from self . values ()
+
+ def all_items ( self ) -> Generator :
+ r """
+ Equivalent to `keys`.
+
+ This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
+
+ See Also:
+ [`all_items`][chanfig.NestedDict.all_items]
+ """
+ yield from self . items ()
+
+ def dropnull ( self ) -> Self :
+ r """
+ Drop key-value pairs with `Null` value.
+
+ Returns:
+ (FlatDict):
+
+ **Alias**:
+
+ + `dropna`
+
+ Examples:
+ >>> d = FlatDict(a=Null, b=Null, c=3)
+ >>> d.dict()
+ {'a': Null, 'b': Null, 'c': 3}
+ >>> d.dropnull().dict()
+ {'c': 3}
+ >>> d.dropna().dict() # alias
+ {'c': 3}
+ """
- main_repr = self . __class__ . __name__ + "("
- if lines :
- # simple one-liner info, which most builtin Modules will use
- if len ( extra_lines ) == 1 and not child_lines :
- main_repr += extra_lines [ 0 ]
- elif len ( child_lines ) == 1 and not extra_lines and len ( child_lines [ 0 ]) < 10 :
- main_repr += child_lines [ 0 ]
- else :
- main_repr += " \n " + " \n " . join ( lines ) + " \n "
-
- main_repr += ")"
- return main_repr
-
- def _add_indent ( self , text : str ) -> str :
- lines = text . split ( " \n " )
- # don't do anything for single-line stuff
- if len ( lines ) == 1 :
- return text
- first = lines . pop ( 0 )
- lines = [( self . getattr ( "indent" , 2 ) * " " ) + line for line in lines ]
- text = " \n " . join ( lines )
- text = first + " \n " + text
- return text
-
- def __format__ ( self , format_spec : str ) -> str :
- return repr ( self . empty ({ k : v . __format__ ( format_spec ) for k , v in self . all_items ()}))
+ return self . empty ({ k : v for k , v in self . all_items () if v is not Null })
+
+ def dropna ( self ) -> Self :
+ r """
+ Alias of [`dropnull`][chanfig.FlatDict.dropnull].
+ """
+ return self . dropnull ()
+
+ @staticmethod
+ def extra_repr () -> str : # pylint: disable=C0116
+ return ""
+
+ def __repr__ ( self ) -> str :
+ extra_lines = []
+ extra_repr = self . extra_repr ()
+ # empty string will be split into list ['']
+ if extra_repr :
+ extra_lines = extra_repr . split ( " \n " )
+ child_lines = []
+ for key , value in self . items ():
+ key_repr = repr ( key )
+ value_repr = repr ( value )
+ value_repr = self . _add_indent ( value_repr )
+ child_lines . append ( f "( { key_repr } ): { value_repr } " )
+ # child_lines.append(f"{key_repr}: {value_repr}")
+ lines = extra_lines + child_lines
- def __hash__ ( self ):
- return hash ( frozenset ( self . items ()))
-
- def _ipython_display_ ( self ): # pragma: no cover
- return repr ( self )
-
- def _ipython_canary_method_should_not_exist_ ( self ): # pragma: no cover
- return None
-
- def aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf ( self ): # pragma: no cover
- return None
-
- def __rich__ ( self ): # pragma: no cover
- return self . __repr__ ()
+ main_repr = self . __class__ . __name__ + "("
+ if lines :
+ # simple one-liner info, which most builtin Modules will use
+ if len ( extra_lines ) == 1 and not child_lines :
+ main_repr += extra_lines [ 0 ]
+ elif len ( child_lines ) == 1 and not extra_lines and len ( child_lines [ 0 ]) < 10 :
+ main_repr += child_lines [ 0 ]
+ else :
+ main_repr += " \n " + " \n " . join ( lines ) + " \n "
+
+ main_repr += ")"
+ return main_repr
+
+ def _add_indent ( self , text : str ) -> str :
+ lines = text . split ( " \n " )
+ # don't do anything for single-line stuff
+ if len ( lines ) == 1 :
+ return text
+ first = lines . pop ( 0 )
+ lines = [( self . getattr ( "indent" , 2 ) * " " ) + line for line in lines ]
+ text = " \n " . join ( lines )
+ text = first + " \n " + text
+ return text
+
+ def __format__ ( self , format_spec : str ) -> str :
+ return repr ( self . empty ({ k : v . __format__ ( format_spec ) for k , v in self . all_items ()}))
+
+ def __hash__ ( self ):
+ return hash ( frozenset ( self . items ()))
+
+ def _ipython_display_ ( self ): # pragma: no cover
+ return repr ( self )
+
+ def _ipython_canary_method_should_not_exist_ ( self ): # pragma: no cover
+ return None
+
+ def aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf ( self ): # pragma: no cover
+ return None
+
+ def __rich__ ( self ): # pragma: no cover
+ return self . __repr__ ()
@@ -4356,25 +4418,25 @@
Source code in chanfig/flat_dict.py
- Python def all_items ( self ) -> Generator :
- r """
- Equivalent to `keys`.
-
- This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
-
- See Also:
- [`all_items`][chanfig.NestedDict.all_items]
- """
- yield from self . items ()
+ Python def all_items ( self ) -> Generator :
+ r """
+ Equivalent to `keys`.
+
+ This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
+
+ See Also:
+ [`all_items`][chanfig.NestedDict.all_items]
+ """
+ yield from self . items ()
@@ -4402,25 +4464,25 @@
Source code in chanfig/flat_dict.py
- Python def all_keys ( self ) -> Generator :
- r """
- Equivalent to `keys`.
-
- This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
-
- See Also:
- [`all_keys`][chanfig.NestedDict.all_keys]
- """
- yield from self . keys ()
+ Python def all_keys ( self ) -> Generator :
+ r """
+ Equivalent to `keys`.
+
+ This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
+
+ See Also:
+ [`all_keys`][chanfig.NestedDict.all_keys]
+ """
+ yield from self . keys ()
@@ -4448,25 +4510,25 @@
Source code in chanfig/flat_dict.py
- Python def all_values ( self ) -> Generator :
- r """
- Equivalent to `keys`.
-
- This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
-
- See Also:
- [`all_values`][chanfig.NestedDict.all_values]
- """
- yield from self . values ()
+ Python def all_values ( self ) -> Generator :
+ r """
+ Equivalent to `keys`.
+
+ This method is provided solely to make methods work on both `FlatDict` and `NestedDict`.
+
+ See Also:
+ [`all_values`][chanfig.NestedDict.all_values]
+ """
+ yield from self . values ()
@@ -4488,15 +4550,15 @@
Source code in chanfig/flat_dict.py
- Python def clone ( self , memo : Mapping | None = None ) -> Self :
- r """
- Alias of [`deepcopy`][chanfig.FlatDict.deepcopy].
- """
- return self . deepcopy ( memo = memo )
+ Python def clone ( self , memo : Mapping | None = None ) -> Self :
+ r """
+ Alias of [`deepcopy`][chanfig.FlatDict.deepcopy].
+ """
+ return self . deepcopy ( memo = memo )
@@ -4555,47 +4617,47 @@
Source code in chanfig/flat_dict.py
- Python def copy ( self ) -> Self :
- r """
- Create a shallow copy of `FlatDict`.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> d.setattr("name", "Chang")
- >>> c = d.copy()
- >>> c.dict()
- {'a': []}
- >>> d.a.append(1)
- >>> c.dict()
- {'a': [1]}
- >>> c.getattr("name")
- 'Chang'
- """
-
- return copy ( self )
+ Python def copy ( self ) -> Self :
+ r """
+ Create a shallow copy of `FlatDict`.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> d.setattr("name", "Chang")
+ >>> c = d.copy()
+ >>> c.dict()
+ {'a': []}
+ >>> d.a.append(1)
+ >>> c.dict()
+ {'a': [1]}
+ >>> c.getattr("name")
+ 'Chang'
+ """
+
+ return copy ( self )
@@ -4648,35 +4710,35 @@
Source code in chanfig/flat_dict.py
- Python def cpu ( self ) -> Self : # pragma: no cover
- r """
- Move all tensors to cpu.
-
- Returns:
- self:
-
- Examples:
- >>> import torch
- >>> d = FlatDict(a=torch.tensor(1))
- >>> d.cpu().dict() # doctest: +SKIP
- {'a': tensor(1, device='cpu')}
- """
-
- return self . to ( TorchDevice ( "cpu" ))
+ Python def cpu ( self ) -> Self : # pragma: no cover
+ r """
+ Move all tensors to cpu.
+
+ Returns:
+ self:
+
+ Examples:
+ >>> import torch
+ >>> d = FlatDict(a=torch.tensor(1))
+ >>> d.cpu().dict() # doctest: +SKIP
+ {'a': tensor(1, device='cpu')}
+ """
+
+ return self . to ( TorchDevice ( "cpu" ))
@@ -4698,15 +4760,15 @@
Source code in chanfig/flat_dict.py
- Python def cuda ( self ) -> Self : # pragma: no cover
- r """
- Alias of [`gpu`][chanfig.FlatDict.gpu].
- """
- return self . gpu ()
+ Python def cuda ( self ) -> Self : # pragma: no cover
+ r """
+ Alias of [`gpu`][chanfig.FlatDict.gpu].
+ """
+ return self . gpu ()
@@ -4771,59 +4833,59 @@
Source code in chanfig/flat_dict.py
- Python def deepcopy ( self , memo : Mapping | None = None ) -> Self : # pylint: disable=W0613
- r """
- Create a deep copy of `FlatDict`.
-
- Returns:
- (FlatDict):
-
- **Alias**:
-
- + `clone`
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> d.setattr("name", "Chang")
- >>> c = d.deepcopy()
- >>> c.dict()
- {'a': []}
- >>> d.a.append(1)
- >>> c.dict()
- {'a': []}
- >>> c.getattr("name")
- 'Chang'
- >>> d == d.clone() # alias
- True
- """
-
- return deepcopy ( self )
+ Python def deepcopy ( self , memo : Mapping | None = None ) -> Self : # pylint: disable=W0613
+ r """
+ Create a deep copy of `FlatDict`.
+
+ Returns:
+ (FlatDict):
+
+ **Alias**:
+
+ + `clone`
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> d.setattr("name", "Chang")
+ >>> c = d.deepcopy()
+ >>> c.dict()
+ {'a': []}
+ >>> d.a.append(1)
+ >>> c.dict()
+ {'a': []}
+ >>> c.getattr("name")
+ 'Chang'
+ >>> d == d.clone() # alias
+ True
+ """
+
+ return deepcopy ( self )
@@ -4887,47 +4949,47 @@
Source code in chanfig/flat_dict.py
- Python def delattr ( self , name : str ) -> None :
- r """
- Delete attribute of `FlatDict`.
-
- Note that it won't delete values in `FlatDict`.
-
- Args:
- name:
-
- Examples:
- >>> d = FlatDict()
- >>> d.setattr('name', 'chang')
- >>> d.getattr('name')
- 'chang'
- >>> d.delattr('name')
- >>> d.getattr('name')
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'name'
- """
-
- del self . __dict__ [ name ]
+ Python def delattr ( self , name : str ) -> None :
+ r """
+ Delete attribute of `FlatDict`.
+
+ Note that it won't delete values in `FlatDict`.
+
+ Args:
+ name:
+
+ Examples:
+ >>> d = FlatDict()
+ >>> d.setattr('name', 'chang')
+ >>> d.getattr('name')
+ 'chang'
+ >>> d.delattr('name')
+ >>> d.getattr('name')
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'name'
+ """
+
+ del self . __dict__ [ name ]
@@ -4998,59 +5060,59 @@
Source code in chanfig/flat_dict.py
- Python def delete ( self , name : Any ) -> None :
- r """
- Delete value from `FlatDict`.
-
- Args:
- name:
-
- Examples:
- >>> d = FlatDict(d=1016, n='chang')
- >>> d.d
- 1016
- >>> d.n
- 'chang'
- >>> d.delete('d')
- >>> d.d
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'd'
- >>> del d.n
- >>> d.n
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'n'
- >>> del d.f
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'f'
- """
-
- dict . __delitem__ ( self , name )
+ Python def delete ( self , name : Any ) -> None :
+ r """
+ Delete value from `FlatDict`.
+
+ Args:
+ name:
+
+ Examples:
+ >>> d = FlatDict(d=1016, n='chang')
+ >>> d.d
+ 1016
+ >>> d.n
+ 'chang'
+ >>> d.delete('d')
+ >>> d.d
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'd'
+ >>> del d.n
+ >>> d.n
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'n'
+ >>> del d.f
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'f'
+ """
+
+ dict . __delitem__ ( self , name )
@@ -5140,53 +5202,53 @@
Source code in chanfig/flat_dict.py
- Python def dict ( self , flatten : bool = False ) -> Mapping | Sequence | Set :
- r """
- Convert `FlatDict` to other `Mapping`.
-
- Args:
- flatten: Whether to flatten [`NestedDict`][chanfig.NestedDict].
-
- Returns:
- (Mapping):
-
- See Also:
- [`to_dict`][chanfig.flat_dict.to_dict]: Implementation of `dict`.
-
- **Alias**:
-
- + `to_dict`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> d.dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- return to_dict ( self , flatten )
+ Python def dict ( self , flatten : bool = False ) -> Mapping | Sequence | Set :
+ r """
+ Convert `FlatDict` to other `Mapping`.
+
+ Args:
+ flatten: Whether to flatten [`NestedDict`][chanfig.NestedDict].
+
+ Returns:
+ (Mapping):
+
+ See Also:
+ [`to_dict`][chanfig.flat_dict.to_dict]: Implementation of `dict`.
+
+ **Alias**:
+
+ + `to_dict`
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> d.dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ return to_dict ( self , flatten )
@@ -5208,15 +5270,15 @@
Source code in chanfig/flat_dict.py
- Python def diff ( self , other : Mapping | Iterable | PathStr , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Alias of [`difference`][chanfig.FlatDict.difference].
- """
- return self . difference ( other , * args , ** kwargs )
+ Python def diff ( self , other : Mapping | Iterable | PathStr , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Alias of [`difference`][chanfig.FlatDict.difference].
+ """
+ return self . difference ( other , * args , ** kwargs )
@@ -5312,34 +5374,7 @@
Source code in chanfig/flat_dict.py
- Python 856
-857
-858
-859
-860
-861
-862
-863
-864
-865
-866
-867
-868
-869
-870
-871
-872
-873
-874
-875
-876
-877
-878
-879
-880
-881
-882
-883
+ Python def difference ( self , other : Mapping | Iterable | PathStr ) -> Self :
- r """
- Difference between `FlatDict` and `other`.
-
- Args:
- other:
-
- Returns:
- (FlatDict):
-
- **Alias**:
-
- + `diff`
-
- Examples:
- >>> d = FlatDict(a=1, b=2, c=3)
- >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
- >>> d.difference(n).dict()
- {'b': 'b', 'c': 'c', 'd': 'd'}
- >>> l = [('c', 3), ('d', 4)]
- >>> d.difference(l).dict()
- {'d': 4}
- >>> d.merge(l).difference("tests/test.yaml").dict()
- {}
- >>> d.difference(1)
- Traceback (most recent call last):
- TypeError: `other=1` should be of type Mapping, Iterable or PathStr, but got <class 'int'>.
- >>> FlatDict(a=1, b=1, c=1).diff(FlatDict(b='b', c='c', d='d')).dict() # alias
- {'b': 'b', 'c': 'c', 'd': 'd'}
- """
+895
+896
+897
+898
+899
+900
+901
+902
+903
+904
+905
+906
+907
+908
+909
+910
+911
+912
+913
+914
+915
+916
+917
+918
+919
+920
+921
+922
def difference ( self , other : Mapping | Iterable | PathStr ) -> Self :
+ r """
+ Difference between `FlatDict` and `other`.
- if isinstance ( other , ( PathLike , str , bytes )):
- other = self . load ( other )
- if isinstance ( other , ( Mapping ,)):
- other = self . empty ( other ) . items ()
- if not isinstance ( other , Iterable ):
- raise TypeError ( f "`other= { other } ` should be of type Mapping, Iterable or PathStr, but got { type ( other ) } ." )
- return self . empty (
- ** { key : value for key , value in other if key not in self or self [ key ] != value } # type: ignore[misc]
- )
+ Args:
+ other:
+
+ Returns:
+ (FlatDict):
+
+ **Alias**:
+
+ + `diff`
+
+ Examples:
+ >>> d = FlatDict(a=1, b=2, c=3)
+ >>> n = {'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> d.difference(n).dict()
+ {'b': 'b', 'c': 'c', 'd': 'd'}
+ >>> l = [('c', 3), ('d', 4)]
+ >>> d.difference(l).dict()
+ {'d': 4}
+ >>> d.merge(l).difference("tests/test.yaml").dict()
+ {}
+ >>> d.difference(1)
+ Traceback (most recent call last):
+ TypeError: `other=1` should be of type Mapping, Iterable or PathStr, but got <class 'int'>.
+ >>> FlatDict(a=1, b=1, c=1).diff(FlatDict(b='b', c='c', d='d')).dict() # alias
+ {'b': 'b', 'c': 'c', 'd': 'd'}
+ """
+
+ if isinstance ( other , ( PathLike , str , bytes )):
+ other = self . load ( other )
+ if isinstance ( other , ( Mapping ,)):
+ other = self . empty ( other ) . items ()
+ if not isinstance ( other , Iterable ):
+ raise TypeError ( f "`other= { other } ` should be of type Mapping, Iterable or PathStr, but got { type ( other ) } ." )
+ return self . empty (
+ ** { key : value for key , value in other if key not in self or self [ key ] != value } # type: ignore[misc]
+ )
@@ -5412,15 +5474,15 @@
Source code in chanfig/flat_dict.py
- Python def dropna ( self ) -> Self :
- r """
- Alias of [`dropnull`][chanfig.FlatDict.dropnull].
- """
- return self . dropnull ()
+ Python def dropna ( self ) -> Self :
+ r """
+ Alias of [`dropnull`][chanfig.FlatDict.dropnull].
+ """
+ return self . dropnull ()
@@ -5480,49 +5542,49 @@
Source code in chanfig/flat_dict.py
- Python def dropnull ( self ) -> Self :
- r """
- Drop key-value pairs with `Null` value.
-
- Returns:
- (FlatDict):
-
- **Alias**:
-
- + `dropna`
-
- Examples:
- >>> d = FlatDict(a=Null, b=Null, c=3)
- >>> d.dict()
- {'a': Null, 'b': Null, 'c': 3}
- >>> d.dropnull().dict()
- {'c': 3}
- >>> d.dropna().dict() # alias
- {'c': 3}
- """
-
- return self . empty ({ k : v for k , v in self . all_items () if v is not Null })
+ Python def dropnull ( self ) -> Self :
+ r """
+ Drop key-value pairs with `Null` value.
+
+ Returns:
+ (FlatDict):
+
+ **Alias**:
+
+ + `dropna`
+
+ Examples:
+ >>> d = FlatDict(a=Null, b=Null, c=3)
+ >>> d.dict()
+ {'a': Null, 'b': Null, 'c': 3}
+ >>> d.dropnull().dict()
+ {'c': 3}
+ >>> d.dropna().dict() # alias
+ {'c': 3}
+ """
+
+ return self . empty ({ k : v for k , v in self . all_items () if v is not Null })
@@ -5544,19 +5606,19 @@
Source code in chanfig/flat_dict.py
- Python def dump ( # pylint: disable=W1113
- self , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
-) -> None :
- r """
- Alias of [`save`][chanfig.FlatDict.save].
- """
- return self . save ( file , method , * args , ** kwargs )
+ Python def dump ( # pylint: disable=W1113
+ self , file : File , method : str = None , * args : Any , ** kwargs : Any # type: ignore[assignment]
+) -> None :
+ r """
+ Alias of [`save`][chanfig.FlatDict.save].
+ """
+ return self . save ( file , method , * args , ** kwargs )
@@ -5621,57 +5683,57 @@
Source code in chanfig/flat_dict.py
- Python @classmethod
-def empty ( cls , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Initialise an empty `FlatDict`.
-
- This method is helpful when you inheriting `FlatDict` with default values defined in `__init__()`.
- As use `type(self)()` in this case would copy all the default values, which might not be desired.
-
- This method will preserve everything in `FlatDict.__class__.__dict__`.
-
- Returns:
- (FlatDict):
-
- See Also:
- [`empty_like`][chanfig.FlatDict.empty_like]
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> c = d.empty()
- >>> c.dict()
- {}
- """
-
- empty = cls . __new__ ( cls )
- empty . merge ( * args , ** kwargs ) # pylint: disable=W0212
- return empty
+ Python @classmethod
+def empty ( cls , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Initialise an empty `FlatDict`.
+
+ This method is helpful when you inheriting `FlatDict` with default values defined in `__init__()`.
+ As use `type(self)()` in this case would copy all the default values, which might not be desired.
+
+ This method will preserve everything in `FlatDict.__class__.__dict__`.
+
+ Returns:
+ (FlatDict):
+
+ See Also:
+ [`empty_like`][chanfig.FlatDict.empty_like]
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> c = d.empty()
+ >>> c.dict()
+ {}
+ """
+
+ empty = cls . __new__ ( cls )
+ empty . merge ( * args , ** kwargs ) # pylint: disable=W0212
+ return empty
@@ -5735,61 +5797,61 @@
Source code in chanfig/flat_dict.py
- Python def empty_like ( self , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Initialise an empty copy of `FlatDict`.
-
- This method will preserve everything in `FlatDict.__class__.__dict__` and `FlatDict.__dict__`.
-
- For example, `property`s are saved in `__dict__`, they will keep their original reference after calling this
- method.
-
- Returns:
- (FlatDict):
-
- See Also:
- [`empty`][chanfig.FlatDict.empty]
-
- Examples:
- >>> d = FlatDict(a=[])
- >>> d.setattr("name", "Chang")
- >>> c = d.empty_like()
- >>> c.dict()
- {}
- >>> c.getattr("name")
- 'Chang'
- """
-
- empty = self . empty ( * args , ** kwargs )
- empty . __dict__ . update ( self . __dict__ )
- return empty
+ Python def empty_like ( self , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Initialise an empty copy of `FlatDict`.
+
+ This method will preserve everything in `FlatDict.__class__.__dict__` and `FlatDict.__dict__`.
+
+ For example, `property`s are saved in `__dict__`, they will keep their original reference after calling this
+ method.
+
+ Returns:
+ (FlatDict):
+
+ See Also:
+ [`empty`][chanfig.FlatDict.empty]
+
+ Examples:
+ >>> d = FlatDict(a=[])
+ >>> d.setattr("name", "Chang")
+ >>> c = d.empty_like()
+ >>> c.dict()
+ {}
+ >>> c.getattr("name")
+ 'Chang'
+ """
+
+ empty = self . empty ( * args , ** kwargs )
+ empty . __dict__ . update ( self . __dict__ )
+ return empty
@@ -5836,34 +5898,7 @@
Source code in chanfig/flat_dict.py
- Python 526
-527
-528
-529
-530
-531
-532
-533
-534
-535
-536
-537
-538
-539
-540
-541
-542
-543
-544
-545
-546
-547
-548
-549
-550
-551
-552
-553
+ Python @classmethod
-def from_dict ( cls , obj : Mapping | Sequence ) -> Any : # pylint: disable=R0911
- r """
- Convert `Mapping` or `Sequence` to `FlatDict`.
-
- Examples:
- >>> FlatDict.from_dict({'a': 1, 'b': 2, 'c': 3})
- FlatDict(
- ('a'): 1
- ('b'): 2
- ('c'): 3
- )
- >>> FlatDict.from_dict([('a', 1), ('b', 2), ('c', 3)])
- FlatDict(
- ('a'): 1
- ('b'): 2
- ('c'): 3
- )
- >>> FlatDict.from_dict([{'a': 1}, {'b': 2}, {'c': 3}])
- [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
- >>> FlatDict.from_dict({1, 2, 3})
- Traceback (most recent call last):
- TypeError: Expected Mapping or Sequence, but got <class 'set'>.
- """
-
- if obj is None :
- return cls ()
- if issubclass ( cls , FlatDict ):
- cls = cls . empty # type: ignore[assignment] # pylint: disable=W0642
- if isinstance ( obj , Mapping ):
- return cls ( obj )
- if isinstance ( obj , Sequence ):
- try :
- return cls ( obj )
- except ValueError :
- return [ cls ( json ) for json in obj ]
- raise TypeError ( f "Expected Mapping or Sequence, but got { type ( obj ) } ." )
+562
+563
+564
+565
+566
+567
+568
+569
+570
+571
+572
+573
+574
+575
+576
+577
+578
+579
+580
+581
+582
+583
+584
+585
+586
+587
+588
+589
@classmethod
+def from_dict ( cls , obj : Mapping | Sequence ) -> Any : # pylint: disable=R0911
+ r """
+ Convert `Mapping` or `Sequence` to `FlatDict`.
+
+ Examples:
+ >>> FlatDict.from_dict({'a': 1, 'b': 2, 'c': 3})
+ FlatDict(
+ ('a'): 1
+ ('b'): 2
+ ('c'): 3
+ )
+ >>> FlatDict.from_dict([('a', 1), ('b', 2), ('c', 3)])
+ FlatDict(
+ ('a'): 1
+ ('b'): 2
+ ('c'): 3
+ )
+ >>> FlatDict.from_dict([{'a': 1}, {'b': 2}, {'c': 3}])
+ [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
+ >>> FlatDict.from_dict({1, 2, 3})
+ Traceback (most recent call last):
+ TypeError: Expected Mapping or Sequence, but got <class 'set'>.
+ """
+
+ if obj is None :
+ return cls ()
+ if issubclass ( cls , FlatDict ):
+ cls = cls . empty # type: ignore[assignment] # pylint: disable=W0642
+ if isinstance ( obj , Mapping ):
+ return cls ( obj )
+ if isinstance ( obj , Sequence ):
+ try :
+ return cls ( obj )
+ except ValueError :
+ return [ cls ( json ) for json in obj ]
+ raise TypeError ( f "Expected Mapping or Sequence, but got { type ( obj ) } ." )
@@ -5966,47 +6028,47 @@
Source code in chanfig/flat_dict.py
- Python @classmethod
-def from_json ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from json file.
-
- This method internally calls `self.from_jsons()` to construct object from json string.
- You may overwrite `from_jsons` in case something is not json serializable.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> d = FlatDict.from_json('tests/test.json')
- >>> d.dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- with cls . open ( file ) as fp : # pylint: disable=C0103
- if isinstance ( file , ( IOBase , IO )):
- return cls . from_jsons ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
- return cls . from_jsons ( fp . read (), * args , ** kwargs )
+ Python @classmethod
+def from_json ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from json file.
+
+ This method internally calls `self.from_jsons()` to construct object from json string.
+ You may overwrite `from_jsons` in case something is not json serializable.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> d = FlatDict.from_json('tests/test.json')
+ >>> d.dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ with cls . open ( file ) as fp : # pylint: disable=C0103
+ if isinstance ( file , ( IOBase , IO )):
+ return cls . from_jsons ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
+ return cls . from_jsons ( fp . read (), * args , ** kwargs )
@@ -6065,41 +6127,41 @@
Source code in chanfig/flat_dict.py
- Python @classmethod
-def from_jsons ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from json string.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> FlatDict.from_jsons('{\n "a": 1,\n "b": 2,\n "c": 3\n}').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_jsons('[["a", 1], ["b", 2], ["c", 3]]').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_jsons('[{"a": 1}, {"b": 2}, {"c": 3}]')
- [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
- """
-
- return cls . from_dict ( json_loads ( string , * args , ** kwargs ))
+ Python @classmethod
+def from_jsons ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from json string.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> FlatDict.from_jsons('{\n "a": 1,\n "b": 2,\n "c": 3\n}').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_jsons('[["a", 1], ["b", 2], ["c", 3]]').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_jsons('[{"a": 1}, {"b": 2}, {"c": 3}]')
+ [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
+ """
+
+ return cls . from_dict ( json_loads ( string , * args , ** kwargs ))
@@ -6156,47 +6218,47 @@
Source code in chanfig/flat_dict.py
- Python @classmethod
-def from_yaml ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from yaml file.
-
- This method internally calls `self.from_yamls()` to construct object from yaml string.
- You may overwrite `from_yamls` in case something is not yaml serializable.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> FlatDict.from_yaml('tests/test.yaml').dict()
- {'a': 1, 'b': 2, 'c': 3}
- """
-
- kwargs . setdefault ( "Loader" , YamlLoader )
- with cls . open ( file ) as fp : # pylint: disable=C0103
- if isinstance ( file , ( IOBase , IO )):
- return cls . from_yamls ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
- return cls . from_dict ( yaml_load ( fp , * args , ** kwargs ))
+ Python @classmethod
+def from_yaml ( cls , file : File , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from yaml file.
+
+ This method internally calls `self.from_yamls()` to construct object from yaml string.
+ You may overwrite `from_yamls` in case something is not yaml serializable.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> FlatDict.from_yaml('tests/test.yaml').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ """
+
+ kwargs . setdefault ( "Loader" , YamlLoader )
+ with cls . open ( file ) as fp : # pylint: disable=C0103
+ if isinstance ( file , ( IOBase , IO )):
+ return cls . from_yamls ( fp . getvalue (), * args , ** kwargs ) # type: ignore[union-attr]
+ return cls . from_dict ( yaml_load ( fp , * args , ** kwargs ))
@@ -6255,43 +6317,43 @@
Source code in chanfig/flat_dict.py
- Python @classmethod
-def from_yamls ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
- r """
- Construct `FlatDict` from yaml string.
-
- Returns:
- (FlatDict):
-
- Examples:
- >>> FlatDict.from_yamls('a: 1\nb: 2\nc: 3\n').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_yamls('- - a\n - 1\n- - b\n - 2\n- - c\n - 3\n').dict()
- {'a': 1, 'b': 2, 'c': 3}
- >>> FlatDict.from_yamls('- a: 1\n- b: 2\n- c: 3\n')
- [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
- """
-
- kwargs . setdefault ( "Loader" , SafeLoader )
- return cls . from_dict ( yaml_load ( string , * args , ** kwargs ))
+ Python @classmethod
+def from_yamls ( cls , string : str , * args : Any , ** kwargs : Any ) -> Self :
+ r """
+ Construct `FlatDict` from yaml string.
+
+ Returns:
+ (FlatDict):
+
+ Examples:
+ >>> FlatDict.from_yamls('a: 1\nb: 2\nc: 3\n').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_yamls('- - a\n - 1\n- - b\n - 2\n- - c\n - 3\n').dict()
+ {'a': 1, 'b': 2, 'c': 3}
+ >>> FlatDict.from_yamls('- a: 1\n- b: 2\n- c: 3\n')
+ [FlatDict(('a'): 1), FlatDict(('b'): 2), FlatDict(('c'): 3)]
+ """
+
+ kwargs . setdefault ( "Loader" , SafeLoader )
+ return cls . from_dict ( yaml_load ( string , * args , ** kwargs ))
@@ -6431,34 +6493,7 @@
Source code in chanfig/flat_dict.py
- Python 208
-209
-210
-211
-212
-213
-214
-215
-216
-217
-218
-219
-220
-221
-222
-223
-224
-225
-226
-227
-228
-229
-230
-231
-232
-233
-234
-235
+ Python def get ( self , name : Any , default : Any = None ) -> Any :
- r """
- Get value from `FlatDict`.
-
- Args:
- name:
- default:
-
- Returns:
- value:
- If `FlatDict` does not contain `name`, return `default`.
-
- Raises:
- KeyError: If `FlatDict` does not contain `name` and `default` is not specified.
- TypeError: If `name` is not hashable.
-
- Examples:
- >>> d = FlatDict(d=1013)
- >>> d.get('d')
- 1013
- >>> d['d']
- 1013
- >>> d.d
- 1013
- >>> d.get('d', None)
- 1013
- >>> d.get('f', 2)
- 2
- >>> d.get('f')
- >>> d.get('f', Null)
- Traceback (most recent call last):
- KeyError: 'f'
- """
-
- if name in self :
- return dict . __getitem__ ( self , name )
- if default is not Null :
- return default
- return self . __missing__ ( name )
+246
+247
+248
+249
+250
+251
+252
+253
+254
+255
+256
+257
+258
+259
+260
+261
+262
+263
+264
+265
+266
+267
+268
+269
+270
+271
+272
+273
def get ( self , name : Any , default : Any = None ) -> Any :
+ r """
+ Get value from `FlatDict`.
+
+ Args:
+ name:
+ default:
+
+ Returns:
+ value:
+ If `FlatDict` does not contain `name`, return `default`.
+
+ Raises:
+ KeyError: If `FlatDict` does not contain `name` and `default` is not specified.
+ TypeError: If `name` is not hashable.
+
+ Examples:
+ >>> d = FlatDict(d=1013)
+ >>> d.get('d')
+ 1013
+ >>> d['d']
+ 1013
+ >>> d.d
+ 1013
+ >>> d.get('d', None)
+ 1013
+ >>> d.get('f', 2)
+ 2
+ >>> d.get('f')
+ >>> d.get('f', Null)
+ Traceback (most recent call last):
+ KeyError: 'f'
+ """
+
+ if name in self :
+ return dict . __getitem__ ( self , name )
+ if default is not Null :
+ return default
+ return self . __missing__ ( name )
@@ -6634,34 +6696,7 @@
Source code in chanfig/flat_dict.py
- Python 367
-368
-369
-370
-371
-372
-373
-374
-375
-376
-377
-378
-379
-380
-381
-382
-383
-384
-385
-386
-387
-388
-389
-390
-391
-392
-393
-394
+ Python def getattr ( self , name : str , default : Any = Null ) -> Any :
- r """
- Get attribute of `FlatDict`.
-
- Note that it won't retrieve value in `FlatDict`,
-
- Args:
- name:
- default:
-
- Returns:
- value: If `FlatDict` does not contain `name`, return `default`.
-
- Raises:
- AttributeError: If `FlatDict` does not contain `name` and `default` is not specified.
-
- Examples:
- >>> d = FlatDict(a=1)
- >>> d.get('a')
- 1
- >>> d.getattr('a')
- Traceback (most recent call last):
- AttributeError: 'FlatDict' object has no attribute 'a'
- >>> d.getattr('b', 2)
- 2
- >>> d.setattr('b', 3)
- >>> d.getattr('b')
- 3
- """
-
- try :
- if name in self . __dict__ :
- return self . __dict__ [ name ]
- for cls in self . __class__ . __mro__ :
- if name in cls . __dict__ :
- return cls . __dict__ [ name ]
- return super () . getattr ( name , default ) # type: ignore[misc]
- except AttributeError :
- if default is not Null :
- return default
- raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
+407
+408
+409
+410
+411
+412
+413
+414
+415
+416
+417
+418
+419
+420
+421
+422
+423
+424
+425
+426
+427
+428
+429
+430
+431
+432
+433
+434
def getattr ( self , name : str , default : Any = Null ) -> Any :
+ r """
+ Get attribute of `FlatDict`.
+
+ Note that it won't retrieve value in `FlatDict`,
+
+ Args:
+ name:
+ default:
+
+ Returns:
+ value: If `FlatDict` does not contain `name`, return `default`.
+
+ Raises:
+ AttributeError: If `FlatDict` does not contain `name` and `default` is not specified.
+
+ Examples:
+ >>> d = FlatDict(a=1)
+ >>> d.get('a')
+ 1
+ >>> d.getattr('a')
+ Traceback (most recent call last):
+ AttributeError: 'FlatDict' object has no attribute 'a'
+ >>> d.getattr('b', 2)
+ 2
+ >>> d.setattr('b', 3)
+ >>> d.getattr('b')
+ 3
+ """
+
+ try :
+ if name in self . __dict__ :
+ return self . __dict__ [ name ]
+ for cls in self . __class__ . __mro__ :
+ if name in cls . __dict__ :
+ return cls . __dict__ [ name ]
+ return super () . getattr ( name , default ) # type: ignore[misc]
+ except AttributeError :
+ if default is not Null :
+ return default
+ raise AttributeError ( f "' { self . __class__ . __name__ } ' object has no attribute ' { name } '" ) from None
@@ -6773,47 +6835,47 @@
Source code in chanfig/flat_dict.py
- Python def gpu ( self ) -> Self : # pragma: no cover
- r """
- Move all tensors to gpu.
-
- Returns:
- self:
-
- **Alias**:
-
- + `cuda`
-
- Examples:
- >>> import torch
- >>> d = FlatDict(a=torch.tensor(1))
- >>> d.gpu().dict() # doctest: +SKIP
- {'a': tensor(1, device='cuda:0')}
- >>> d.cuda().dict() # alias # doctest: +SKIP
- {'a': tensor(1, device='cuda:0')}
- """
-
- return self . to ( TorchDevice ( "cuda" ))
+ Python def gpu ( self ) -> Self : # pragma: no cover
+ r """
+ Move all tensors to gpu.
+
+ Returns:
+ self:
+
+ **Alias**:
+
+ + `cuda`
+
+ Examples:
+ >>> import torch
+ >>> d = FlatDict(a=torch.tensor(1))
+ >>> d.gpu().dict() # doctest: +SKIP
+ {'a': tensor(1, device='cuda:0')}
+ >>> d.cuda().dict() # alias # doctest: +SKIP
+ {'a': tensor(1, device='cuda:0')}
+ """
+
+ return self . to ( TorchDevice ( "cuda" ))
@@ -6898,57 +6960,57 @@
Source code in chanfig/flat_dict.py
- Python def hasattr ( self , name : str ) -> bool :
- r """
- Determine if an attribute exists in `FlatDict`.
-
- Args:
- name:
-
- Returns:
- (bool):
-
- Examples:
- >>> d = FlatDict()
- >>> d.setattr('name', 'chang')
- >>> d.hasattr('name')
- True
- >>> d.delattr('name')
- >>> d.hasattr('name')
- False
- """
-
- try :
- if name in self . __dict__ or name in self . __class__ . __dict__ :
- return True
- return super () . hasattr ( name ) # type: ignore[misc]
- except AttributeError :
- return False
+