pytorch-lightning

Форк
0
50 строк · 1.5 Кб
1
# Copyright The Lightning AI team.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

15
from typing import Any, Dict, Optional
16

17

18
class AttributeDict(Dict):
19
    """Extended dictionary accessible with dot notation.
20

21
    >>> ad = AttributeDict({'key1': 1, 'key2': 'abc'})
22
    >>> ad.key1
23
    1
24
    >>> ad.update({'my-key': 3.14})
25
    >>> ad.update(new_key=42)
26
    >>> ad.key1 = 2
27
    >>> ad
28
    "key1":    2
29
    "key2":    abc
30
    "my-key":  3.14
31
    "new_key": 42
32

33
    """
34

35
    def __getattr__(self, key: str) -> Optional[Any]:
36
        try:
37
            return self[key]
38
        except KeyError as exp:
39
            raise AttributeError(f'Missing attribute "{key}"') from exp
40

41
    def __setattr__(self, key: str, val: Any) -> None:
42
        self[key] = val
43

44
    def __repr__(self) -> str:
45
        if not len(self):
46
            return ""
47
        max_key_length = max(len(str(k)) for k in self)
48
        tmp_name = "{:" + str(max_key_length + 3) + "s} {}"
49
        rows = [tmp_name.format(f'"{n}":', self[n]) for n in sorted(self.keys())]
50
        return "\n".join(rows)
51

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.