Skip to content

Commit 6a41a6b

Browse files
committed
p310 code simplify
1 parent 1c71855 commit 6a41a6b

File tree

5 files changed

+62
-49
lines changed

5 files changed

+62
-49
lines changed

.vscode/settings.json

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,30 @@
11
{
22
// Python settings
3-
"python.defaultInterpreterPath": "./venv/bin/python",
3+
"python.analysis.diagnosticSeverityOverrides": {
4+
"reportGeneralTypeIssues": "none",
5+
"reportOptionalMemberAccess": "none",
6+
"reportOptionalSubscript": "none",
7+
"reportOptionalOperand": "none",
8+
"reportOptionalIterable": "none",
9+
"reportUnknownMemberType": "none",
10+
"reportUnknownArgumentType": "none",
11+
"reportUnknownVariableType": "none",
12+
"reportUnknownParameterType": "none",
13+
"reportMissingTypeStubs": "none",
14+
"reportUnknownLambdaType": "none",
15+
"reportImportCycles": "none",
16+
"reportOptionalCall": "none",
17+
"reportOptionalContextManager": "none",
18+
"reportTypedDictNotRequiredAccess": "none",
19+
"reportArgumentType": "none",
20+
"reportOperatorIssue": "none",
21+
"reportAttributeAccessIssue": "none",
22+
"reportCallIssue": "none"
23+
},
24+
"python.analysis.typeCheckingMode": "basic",
425
// Ruff settings
526
"ruff.enable": true,
627
"ruff.lint.enable": true,
7-
"ruff.format.enable": true,
828
// Editor settings
929
"editor.formatOnSave": true,
1030
"editor.codeActionsOnSave": {

cobaya/component.py

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,27 @@
1+
import inspect
12
import os
23
import sys
34
import time
4-
import inspect
5+
from importlib import import_module, resources
56
from inspect import cleandoc
7+
from typing import List, Optional, Set, Union, get_type_hints
8+
69
from packaging import version
7-
from importlib import import_module, resources
8-
from typing import Optional, Union, List, Set, get_type_hints
910

11+
import cobaya
12+
from cobaya.conventions import cobaya_package, kinds, reserved_attributes
1013
from cobaya.log import HasLogger, LoggedError, get_logger
11-
from cobaya.typing import Any, InfoDict, InfoDictIn, empty_dict, validate_type
14+
from cobaya.mpi import is_main_process
1215
from cobaya.tools import (
13-
resolve_packages_path,
14-
load_module,
16+
VersionCheckError,
17+
deepcopy_where_possible,
1518
get_base_classes,
1619
get_internal_class_component_name,
17-
deepcopy_where_possible,
18-
VersionCheckError,
20+
load_module,
21+
resolve_packages_path,
1922
)
20-
from cobaya.conventions import kinds, cobaya_package, reserved_attributes
21-
from cobaya.yaml import yaml_load_file, yaml_dump, yaml_load
22-
from cobaya.mpi import is_main_process
23-
import cobaya
23+
from cobaya.typing import Any, InfoDict, InfoDictIn, empty_dict, validate_type
24+
from cobaya.yaml import yaml_dump, yaml_load, yaml_load_file
2425

2526

2627
class Timer:
@@ -249,7 +250,7 @@ def get_class_options(cls, input_options=empty_dict) -> InfoDict:
249250
@classmethod
250251
def get_defaults(
251252
cls, return_yaml=False, yaml_expand_defaults=True, input_options=empty_dict
252-
):
253+
) -> dict | str:
253254
"""
254255
Return defaults for this component_or_class, with syntax:
255256
@@ -340,15 +341,7 @@ def get_annotations(cls) -> InfoDict:
340341
for base in cls.__bases__:
341342
if issubclass(base, HasDefaults) and base is not HasDefaults:
342343
d.update(base.get_annotations())
343-
344-
# from Python 10 should use just cls.__annotations__
345-
d.update(
346-
{
347-
k: v
348-
for k, v in cls.__dict__.get("__annotations__", {}).items()
349-
if not k.startswith("_")
350-
}
351-
)
344+
d.update(cls.__annotations__)
352345
return d
353346

354347

cobaya/functions.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import numpy as np
21
import logging
2+
3+
import numpy as np
34
import scipy
45

56
try:
@@ -17,7 +18,7 @@
1718
else:
1819
import warnings
1920

20-
def random_SO_N(dim, random_state):
21+
def random_SO_N(dim, *, random_state=None):
2122
"""
2223
Draw random samples from SO(N).
2324
Equivalent to scipy function but about 10x faster

cobaya/typing.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,12 @@
1-
from typing import Dict, Any, Optional, Union, Type, TypedDict, Literal
2-
from collections.abc import Mapping, Callable, Sequence, Iterable
3-
from types import MappingProxyType
41
import contextlib
5-
import typing
62
import numbers
7-
import numpy as np
83
import sys
4+
import typing
5+
from collections.abc import Callable, Iterable, Mapping, Sequence
6+
from types import MappingProxyType, UnionType
7+
from typing import Any, Dict, Literal, Optional, Type, TypedDict, Union
98

10-
# Import UnionType for Python 3.10+ compatibility
11-
try:
12-
from types import UnionType
13-
except ImportError:
14-
# Python < 3.10
15-
UnionType = None
9+
import numpy as np
1610

1711
InfoDict = dict[str, Any]
1812
InfoDictIn = Mapping[str, Any]
@@ -201,8 +195,7 @@ def validate_type(expected_type: type, value: Any, path: str = ""):
201195
):
202196
# complex types like Dict[str, float] etc.
203197

204-
# Handle both typing.Union and types.UnionType (Python 3.10+)
205-
if origin is Union or (UnionType is not None and origin is UnionType):
198+
if origin is Union or origin is UnionType:
206199
errors = []
207200
for t in args:
208201
try:

docs/conf.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@
1515
# add these directories to sys.path here. If the directory is relative to the
1616
# documentation root, use os.path.abspath to make it absolute, like shown here.
1717

18+
import ast
1819
import os
1920
import sys
20-
import ast
21+
2122
import yaml
2223

2324
project = "cobaya"
@@ -73,13 +74,17 @@
7374

7475
# General information about the project.
7576

76-
fields = {"__year__": None, "__author__": None, "__version__": None}
77+
fields = {"__year__": "", "__author__": "", "__version__": ""}
7778

7879
with open(f"../{project}/__init__.py") as f:
7980
tree = ast.parse(f.read())
8081

8182
for node in ast.walk(tree):
82-
if isinstance(node, ast.Assign) and node.targets[0].id in fields:
83+
if (
84+
isinstance(node, ast.Assign)
85+
and isinstance(node.targets[0], ast.Name)
86+
and node.targets[0].id in fields
87+
):
8388
fields[node.targets[0].id] = ast.literal_eval(node.value)
8489

8590
copyright = fields["__year__"] + " " + fields["__author__"]
@@ -94,15 +99,14 @@
9499
# The full version, including alpha/beta/rc tags.
95100
release = version
96101

97-
from cobaya.tools import get_available_internal_classes
98-
from cobaya.likelihood import Likelihood
99-
from cobaya.theory import Theory
100-
from cobaya.sampler import Sampler
101-
102102
# Config of the inheritance diagram
103-
104103
from sphinx.ext import inheritance_diagram
105104

105+
from cobaya.likelihood import Likelihood
106+
from cobaya.sampler import Sampler
107+
from cobaya.theory import Theory
108+
from cobaya.tools import get_available_internal_classes
109+
106110
inheritance_graph_attrs = dict(rankdir="LR", size='""')
107111

108112
# change inheritance diagram to pull all internal component classes
@@ -119,7 +123,9 @@ def import_classes(name, currmodule):
119123
return old_import(name, currmodule)
120124

121125

122-
def class_name(self, cls, parts, aliases):
126+
def class_name(
127+
self, cls: type, parts: int = 0, aliases: dict[str, str] | None = None
128+
) -> str:
123129
if issubclass(cls, bases) and cls not in bases:
124130
name = cls.get_qualified_class_name()
125131
if name.startswith("_") or name.startswith(".") or name.startswith("likelihood."):

0 commit comments

Comments
 (0)