Skip to content

Commit

Permalink
Merge pull request #28 from EwoutH/pyupgrade-3
Browse files Browse the repository at this point in the history
pyupgrade: Update codebase to Python 3 syntax and features
  • Loading branch information
michelbierlaire authored Mar 27, 2024
2 parents 04297be + 1c08b10 commit 8c4975a
Show file tree
Hide file tree
Showing 11 changed files with 32 additions and 33 deletions.
2 changes: 1 addition & 1 deletion src/biogeme/biogeme.py
Original file line number Diff line number Diff line change
Expand Up @@ -1295,7 +1295,7 @@ def _load_saved_iteration(self) -> None:
betas[ell[0].strip()] = float(ell[1])
self.change_init_values(betas)
logger.info(f"Parameter values restored from {filename}")
except IOError:
except OSError:
logger.info(f"Cannot read file {filename}. Statement is ignored.")

def set_random_init_values(self, default_bound: float = 100.0) -> None:
Expand Down
4 changes: 2 additions & 2 deletions src/biogeme/default_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
"""

from __future__ import annotations
from typing import NamedTuple, Type, Callable

import numpy as np
from typing import NamedTuple, Callable

import biogeme.check_parameters as cp
import biogeme.optimization as opt
Expand All @@ -23,7 +23,7 @@
class ParameterTuple(NamedTuple):
name: str
value: ParameterValue
type: Type
type: type
section: str
description: str
check: tuple[Callable[[ParameterValue], tuple[bool, str | None]], ...]
Expand Down
6 changes: 3 additions & 3 deletions src/biogeme/expressions/base_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def getStatusIdManager(self) -> tuple[set[str], set[str]]:
"""Kept for backward compatibility"""
pass

def prepare(self, database: "Database", number_of_draws: int) -> None:
def prepare(self, database: Database, number_of_draws: int) -> None:
"""Prepare the expression to be evaluated
:param database: Biogeme database
Expand Down Expand Up @@ -1376,7 +1376,7 @@ def set_estimated_values(self, betas: dict[str, float]):

def dict_of_catalogs(
self, ignore_synchronized: bool = False
) -> dict[str, 'Catalog']:
) -> dict[str, Catalog]:
"""Returns a dict with all catalogs in the expression.
:return: dict with all the catalogs
Expand Down Expand Up @@ -1489,7 +1489,7 @@ def select_expression(self, controller_name: str, index: int):

self.central_controller.set_controller(controller_name, index)

def set_of_multiple_expressions(self) -> set['MultipleExpression']:
def set_of_multiple_expressions(self) -> set[MultipleExpression]:
"""Set of the multiple expressions found in the current expression
:return: a set of descriptions of the multiple expressions
Expand Down
10 changes: 5 additions & 5 deletions src/biogeme/expressions/elementary_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def check_draws(self) -> set[str]:
"""
return {self.name}

def set_id_manager(self, id_manager: 'IdManager | None' = None):
def set_id_manager(self, id_manager: IdManager | None = None):
"""The ID manager contains the IDs of the elementary expressions.
It is externally created, as it may need to coordinate the
Expand Down Expand Up @@ -259,7 +259,7 @@ def check_panel_trajectory(self) -> set[str]:
"""
return {self.name}

def set_id_manager(self, id_manager: 'IdManager | None' = None):
def set_id_manager(self, id_manager: IdManager | None = None):
"""The ID manager contains the IDs of the elementary expressions.
It is externally created, as it may need to coordinate the
Expand Down Expand Up @@ -291,7 +291,7 @@ def dict_of_elementary_expression(
return {self.name: self}
return {}

def audit(self, database: 'Database | None' = None) -> tuple[list[str], list[str]]:
def audit(self, database: Database | None = None) -> tuple[list[str], list[str]]:
"""Performs various checks on the expressions.
:param database: database object
Expand Down Expand Up @@ -431,7 +431,7 @@ def check_rv(self) -> set[str]:
"""
return {self.name}

def set_id_manager(self, id_manager: 'IdManager | None' = None):
def set_id_manager(self, id_manager: IdManager | None = None):
"""The ID manager contains the IDs of the elementary expressions.
It is externally created, as it may need to coordinate the
Expand Down Expand Up @@ -587,7 +587,7 @@ def __init__(
self.status = status
self.betaId = None

def set_id_manager(self, id_manager: 'IdManager | None'):
def set_id_manager(self, id_manager: IdManager | None):
"""The ID manager contains the IDs of the elementary expressions.
It is externally created, as it may need to coordinate the
Expand Down
3 changes: 1 addition & 2 deletions src/biogeme/expressions/idmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
TYPE_CHECKING,
TypeVar,
Generic,
Type,
Iterable,
)

Expand Down Expand Up @@ -56,7 +55,7 @@ class ElementsTuple(Generic[T], _ElementsTuple):
logger = logging.getLogger(__name__)


def expressions_names_indices(dict_of_elements: dict[str, Type[T]]) -> ElementsTuple[T]:
def expressions_names_indices(dict_of_elements: dict[str, type[T]]) -> ElementsTuple[T]:
"""Assigns consecutive indices to expressions
:param dict_of_elements: dictionary of expressions. The keys
Expand Down
16 changes: 8 additions & 8 deletions src/biogeme/nests.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import itertools
import logging
from dataclasses import dataclass
from typing import Union, Iterator, Any, Optional
from typing import Iterator, Any

import numpy as np
import pandas as pd
Expand All @@ -36,7 +36,7 @@ class OneNestForNestedLogit:

nest_param: Expression | float
list_of_alternatives: list[int]
name: Optional[str] = None
name: str | None = None

@classmethod
def from_tuple(cls, the_tuple: OldOneNestForNestedLogit) -> OneNestForNestedLogit:
Expand Down Expand Up @@ -77,7 +77,7 @@ def generate_expression(value: Expression | float) -> Expression:

def get_alpha_values(
the_dict: dict[int, Expression | float],
parameters: Optional[dict[str, float]] = None,
parameters: dict[str, float] | None = None,
) -> dict[int, float]:
"""If the dictionary contains float, they are transformed into a
numerical expression.
Expand Down Expand Up @@ -106,7 +106,7 @@ class OneNestForCrossNestedLogit:

nest_param: Expression | float
dict_of_alpha: dict[int, Expression | float]
name: Optional[str] = None
name: str | None = None

@classmethod
def from_tuple(
Expand Down Expand Up @@ -174,7 +174,7 @@ def __init__(

def __getitem__(
self, index: int
) -> Union[OneNestForNestedLogit, OneNestForCrossNestedLogit]:
) -> OneNestForNestedLogit | OneNestForCrossNestedLogit:
if index < 0 or index >= len(self.tuple_of_nests):
raise IndexError(
f'Index out of bounds. Valid indices are between 0 and '
Expand All @@ -200,9 +200,9 @@ def check_union(self) -> tuple[bool, str]:

# Union Check: The union of all lists should be equal to choice_set

union_of_lists = set(
union_of_lists = {
i for nest in self.tuple_of_nests for i in nest.list_of_alternatives
)
}
union_of_lists |= set(self.alone)
if union_of_lists != set(self.choice_set):
missing_values = set(self.choice_set) - union_of_lists # set difference
Expand Down Expand Up @@ -400,7 +400,7 @@ def get_alpha_values(self, alternative_id: int) -> dict[str, float]:
:raise: BiogemeError is one alpha is a non-numeric expression
"""

def get_value(alpha: Union[Expression, float, int]) -> float:
def get_value(alpha: Expression | float | int) -> float:
"""Returns a float, irrespectively of the original type
:param alpha: alpha parameter
Expand Down
2 changes: 1 addition & 1 deletion src/biogeme/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def read_file(self, file_name: str):
self.file_name = DEFAULT_FILE_NAME if file_name is None else file_name

try:
with open(self.file_name, 'r', encoding='utf-8') as f:
with open(self.file_name, encoding='utf-8') as f:
logger.debug(f'Parameter file: {os.path.abspath(self.file_name)}')
content = f.read()
self.document = tk.parse(content)
Expand Down
2 changes: 1 addition & 1 deletion src/biogeme/singleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ class Singleton(type):

def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
2 changes: 1 addition & 1 deletion src/biogeme/specification.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def configure_expression(self) -> None:
self.expression.configure_catalogs(self.configuration)

@classmethod
def default_specification(cls) -> 'Specification':
def default_specification(cls) -> Specification:
"""Alternative constructor for generate the default specification"""
cls.expression.reset_expression_selection()
the_config = cls.expression.current_configuration()
Expand Down
2 changes: 1 addition & 1 deletion tests/functions/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def test_temporary_file(self):
with biogeme.tools.files.TemporaryFile() as filename:
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
with open(filename, 'r', encoding='utf-8') as f:
with open(filename, encoding='utf-8') as f:
check = f.read()
self.assertEqual(content, check)

Expand Down
16 changes: 8 additions & 8 deletions webpage/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def get_section(content):
all_html = ''
id = 0
for card_title, card_paragraphs in content.items():
with open(CARD_FILE, 'r', encoding='utf-8') as f:
with open(CARD_FILE, encoding='utf-8') as f:
html = f.read()
text = ''
for p in card_paragraphs:
Expand All @@ -45,7 +45,7 @@ def get_faq():
id = 0
for question, answer in faq.items():
id += 1
with open(FAQ_FILE, 'r', encoding='utf-8') as f:
with open(FAQ_FILE, encoding='utf-8') as f:
html = f.read()
replacements = {
'__ID__': str(id),
Expand All @@ -58,7 +58,7 @@ def get_faq():

def get_special(content):
all_html = ''
with open(SPECIAL_FILE, 'r', encoding='utf-8') as f:
with open(SPECIAL_FILE, encoding='utf-8') as f:
html = f.read()

for special_title, special_content in content.items():
Expand All @@ -74,7 +74,7 @@ def get_special(content):
def get_portfolio_grid(doc):
all_html = ''
for data, values in doc.items():
with open(PORTFOLIO_GRID_ITEM, 'r') as f:
with open(PORTFOLIO_GRID_ITEM) as f:
html = f.read()
replacements = {
'__ID__': data,
Expand All @@ -92,7 +92,7 @@ def get_portfolio_grid(doc):
def get_portfolio_modals(doc):
all_html = ''
for data, values in doc.items():
with open(PORTFOLIO_MODAL, 'r', encoding='utf-8') as f:
with open(PORTFOLIO_MODAL, encoding='utf-8') as f:
html = f.read()
replacements = {
'__ID__': data,
Expand All @@ -107,14 +107,14 @@ def get_portfolio_modals(doc):
return all_html


with open(DATA_FILE, 'r', encoding='utf-8') as f:
with open(DATA_FILE, encoding='utf-8') as f:
text = f.read()
doc = tk.parse(text)

with open(HTML_FILE, 'r', encoding='utf-8') as f:
with open(HTML_FILE, encoding='utf-8') as f:
html = f.read()

with open(PORTFOLIO_FILE, 'r', encoding='utf-8') as f:
with open(PORTFOLIO_FILE, encoding='utf-8') as f:
portfolio_html = f.read()

portfolio_html = replace(
Expand Down

0 comments on commit 8c4975a

Please sign in to comment.