Skip to content

Commit eb2bf7e

Browse files
committed
Merge branch 'flake8' into MERGE-4.1.0.rc2
2 parents 8e8c056 + f2c674a commit eb2bf7e

8 files changed

Lines changed: 69 additions & 37 deletions

File tree

.pre-commit-config.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ repos:
2020
rev: '7.2.0'
2121
hooks:
2222
- id: flake8
23+
additional_dependencies:
24+
- Flake8-pyproject
2325

2426
- repo: https://github.com/codespell-project/codespell
2527
rev: v2.4.1

OMPython/ModelicaSystem.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -914,7 +914,8 @@ def getSimulationOptions(self, names: Optional[str | list[str]] = None) -> dict[
914914
915915
Examples:
916916
>>> mod.getSimulationOptions()
917-
{'startTime': '0', 'stopTime': '1.234', 'stepSize': '0.002', 'tolerance': '1.1e-08', 'solver': 'dassl', 'outputFormat': 'mat'}
917+
{'startTime': '0', 'stopTime': '1.234',
918+
'stepSize': '0.002', 'tolerance': '1.1e-08', 'solver': 'dassl', 'outputFormat': 'mat'}
918919
>>> mod.getSimulationOptions("stopTime")
919920
['1.234']
920921
>>> mod.getSimulationOptions(["tolerance", "stopTime"])
@@ -1099,8 +1100,10 @@ def simulate(
10991100
Examples:
11001101
mod.simulate()
11011102
mod.simulate(resultfile="a.mat")
1102-
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10") # set runtime simulation flags, deprecated
1103-
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}}) # using simargs
1103+
# set runtime simulation flags, deprecated
1104+
mod.simulate(simflags="-noEventEmit -noRestart -override=e=0.3,g=10")
1105+
# using simargs
1106+
mod.simulate(simargs={"noEventEmit": None, "noRestart": None, "override": "override": {"e": 0.3, "g": 10}})
11041107
"""
11051108

11061109
if resultfile is None:
@@ -1414,7 +1417,8 @@ def setSimulationOptions(
14141417
) -> bool:
14151418
"""
14161419
This method is used to set simulation options. It can be called:
1417-
with a sequence of simulation options name and assigning corresponding values as arguments as show in the example below:
1420+
with a sequence of simulation options name and assigning corresponding values as arguments as show in the
1421+
example below:
14181422
usage
14191423
>>> setSimulationOptions("Name=value") # depreciated
14201424
>>> setSimulationOptions(["Name1=value1","Name2=value2"]) # depreciated
@@ -1438,7 +1442,8 @@ def setLinearizationOptions(
14381442
) -> bool:
14391443
"""
14401444
This method is used to set linearization options. It can be called:
1441-
with a sequence of linearization options name and assigning corresponding value as arguments as show in the example below
1445+
with a sequence of linearization options name and assigning corresponding value as arguments as show in the
1446+
example below
14421447
usage
14431448
>>> setLinearizationOptions("Name=value") # depreciated
14441449
>>> setLinearizationOptions(["Name1=value1","Name2=value2"]) # depreciated
@@ -1462,7 +1467,8 @@ def setOptimizationOptions(
14621467
) -> bool:
14631468
"""
14641469
This method is used to set optimization options. It can be called:
1465-
with a sequence of optimization options name and assigning corresponding values as arguments as show in the example below:
1470+
with a sequence of optimization options name and assigning corresponding values as arguments as show in the
1471+
example below:
14661472
usage
14671473
>>> setOptimizationOptions("Name=value") # depreciated
14681474
>>> setOptimizationOptions(["Name1=value1","Name2=value2"]) # depreciated
@@ -1606,7 +1612,8 @@ def convertMo2Fmu(
16061612
Examples:
16071613
>>> mod.convertMo2Fmu()
16081614
'/tmp/tmpmhfx9umo/CauerLowPassAnalog.fmu'
1609-
>>> mod.convertMo2Fmu(version="2.0", fmuType="me|cs|me_cs", fileNamePrefix="<default>", includeResources=True)
1615+
>>> mod.convertMo2Fmu(version="2.0", fmuType="me|cs|me_cs", fileNamePrefix="<default>",
1616+
includeResources=True)
16101617
'/tmp/tmpmhfx9umo/CauerLowPassAnalog.fmu'
16111618
"""
16121619

OMPython/OMCSession.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
import pyparsing
5959

6060
# TODO: replace this with the new parser
61-
from OMPython.OMTypedParser import parseString as om_parser_typed
61+
from OMPython.OMTypedParser import om_parser_typed
6262
from OMPython.OMParser import om_parser_basic
6363

6464
# define logger using the current module name as ID

OMPython/OMTypedParser.py

Lines changed: 43 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
__status__ = "Prototype"
3232
__maintainer__ = "https://openmodelica.org"
3333

34+
from typing import Any
35+
3436
from pyparsing import (
3537
Combine,
3638
Dict,
@@ -52,45 +54,45 @@
5254
)
5355

5456

55-
def convertNumbers(s, l, toks):
57+
def convert_numbers(s, loc, toks):
5658
n = toks[0]
5759
try:
5860
return int(n)
5961
except ValueError:
6062
return float(n)
6163

6264

63-
def convertString2(s, s2):
65+
def convert_string2(s, s2):
6466
tmp = s2[0].replace("\\\"", "\"")
6567
tmp = tmp.replace("\"", "\\\"")
6668
tmp = tmp.replace("\'", "\\'")
6769
tmp = tmp.replace("\f", "\\f")
6870
tmp = tmp.replace("\n", "\\n")
6971
tmp = tmp.replace("\r", "\\r")
7072
tmp = tmp.replace("\t", "\\t")
71-
return "'"+tmp+"'"
73+
return "'" + tmp + "'"
7274

7375

74-
def convertString(s, s2):
76+
def convert_string(s, s2):
7577
return s2[0].replace("\\\"", '"')
7678

7779

78-
def convertDict(d):
80+
def convert_dict(d):
7981
return dict(d[0])
8082

8183

82-
def convertTuple(t):
84+
def convert_tuple(t):
8385
return tuple(t[0])
8486

8587

86-
def evaluateExpression(s, loc, toks):
88+
def evaluate_expression(s, loc, toks):
8789
# Convert the tokens (ParseResults) into a string expression
8890
flat_list = [item for sublist in toks[0] for item in sublist]
8991
expr = "".join(flat_list)
9092
try:
9193
# Evaluate the expression safely
9294
return eval(expr)
93-
except Exception:
95+
except (SyntaxError, NameError):
9496
return expr
9597

9698

@@ -102,42 +104,60 @@ def evaluateExpression(s, loc, toks):
102104
(Word("*/", exact=1), 2, opAssoc.LEFT),
103105
(Word("+-", exact=1), 2, opAssoc.LEFT),
104106
],
105-
).setParseAction(evaluateExpression)
107+
).set_parse_action(evaluate_expression)
106108

107109
omcRecord = Forward()
108110
omcValue = Forward()
109111

110112
# pyparsing's replace_with (and thus replaceWith) has incorrect type
111113
# annotation: https://github.com/pyparsing/pyparsing/issues/602
112-
TRUE = Keyword("true").setParseAction(replaceWith(True)) # type: ignore
113-
FALSE = Keyword("false").setParseAction(replaceWith(False)) # type: ignore
114-
NONE = (Keyword("NONE") + Suppress("(") + Suppress(")")).setParseAction(replaceWith(None)) # type: ignore
114+
TRUE = Keyword("true").set_parse_action(replaceWith(True)) # type: ignore
115+
FALSE = Keyword("false").set_parse_action(replaceWith(False)) # type: ignore
116+
NONE = (Keyword("NONE") + Suppress("(") + Suppress(")")).set_parse_action(replaceWith(None)) # type: ignore
115117
SOME = (Suppress(Keyword("SOME")) + Suppress("(") + omcValue + Suppress(")"))
116118

117-
omcString = QuotedString(quoteChar='"', escChar='\\', multiline=True).setParseAction(convertString)
119+
omcString = QuotedString(quoteChar='"', escChar='\\', multiline=True).set_parse_action(convert_string)
118120
omcNumber = Combine(Optional('-') + ('0' | Word('123456789', nums)) +
119121
Optional('.' + Word(nums)) +
120122
Optional(Word('eE', exact=1) + Word(nums + '+-', nums)))
121123

122124
# ident = Word(alphas + "_", alphanums + "_") | Combine("'" + Word(alphanums + "!#$%&()*+,-./:;<>=?@[]^{}|~ ") + "'")
123-
ident = Word(alphas + "_", alphanums + "_") | QuotedString(quoteChar='\'', escChar='\\').setParseAction(convertString2)
125+
ident = (Word(alphas + "_", alphanums + "_")
126+
| QuotedString(quoteChar='\'', escChar='\\').set_parse_action(convert_string2))
124127
fqident = Forward()
125128
fqident << ((ident + "." + fqident) | ident)
126129
omcValues = delimitedList(omcValue)
127-
omcTuple = Group(Suppress('(') + Optional(omcValues) + Suppress(')')).setParseAction(convertTuple)
128-
omcArray = Group(Suppress('{') + Optional(omcValues) + Suppress('}')).setParseAction(convertTuple)
129-
omcArraySpecialTypes = Group(Suppress('{') + delimitedList(arrayDimension) + Suppress('}')).setParseAction(convertTuple)
130-
omcValue << (omcString | omcNumber | omcRecord | omcArray | omcArraySpecialTypes | omcTuple | SOME | TRUE | FALSE | NONE | Combine(fqident))
130+
omcTuple = Group(Suppress('(') + Optional(omcValues) + Suppress(')')).set_parse_action(convert_tuple)
131+
omcArray = Group(Suppress('{') + Optional(omcValues) + Suppress('}')).set_parse_action(convert_tuple)
132+
omcArraySpecialTypes = Group(Suppress('{')
133+
+ delimitedList(arrayDimension)
134+
+ Suppress('}')).set_parse_action(convert_tuple)
135+
omcValue << (omcString
136+
| omcNumber
137+
| omcRecord
138+
| omcArray
139+
| omcArraySpecialTypes
140+
| omcTuple
141+
| SOME
142+
| TRUE
143+
| FALSE
144+
| NONE
145+
| Combine(fqident))
131146
recordMember = delimitedList(Group(ident + Suppress('=') + omcValue))
132-
omcRecord << Group(Suppress('record') + Suppress(fqident) + Dict(recordMember) + Suppress('end') + Suppress(fqident) + Suppress(';')).setParseAction(convertDict)
147+
omcRecord << Group(Suppress('record')
148+
+ Suppress(fqident)
149+
+ Dict(recordMember)
150+
+ Suppress('end')
151+
+ Suppress(fqident)
152+
+ Suppress(';')).set_parse_action(convert_dict)
133153

134154
omcGrammar = Optional(omcValue) + StringEnd()
135155

136-
omcNumber.setParseAction(convertNumbers)
156+
omcNumber.set_parse_action(convert_numbers)
137157

138158

139-
def parseString(string):
140-
res = omcGrammar.parseString(string)
159+
def om_parser_typed(string) -> Any:
160+
res = omcGrammar.parse_string(string)
141161
if len(res) == 0:
142-
return
162+
return None
143163
return res[0]

pyproject.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,8 @@ Documentation = "https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/ompy
3232
Issues = "https://github.com/OpenModelica/OMPython/issues"
3333
"Release Notes" = "https://github.com/OpenModelica/OMPython/releases"
3434
Download = "https://pypi.org/project/OMPython/#files"
35+
36+
[tool.flake8]
37+
max-line-length = 120
38+
extend-ignore = [
39+
]

setup.cfg

Lines changed: 0 additions & 2 deletions
This file was deleted.

tests/test_linearization.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,12 +76,12 @@ def test_getters(tmp_path):
7676

7777
mod.setInputs(u1=10, u2=0)
7878
[A, B, C, D] = mod.linearize()
79-
g = float(mod.getParameters("g")[0])
80-
l = float(mod.getParameters("l")[0])
79+
param_g = float(mod.getParameters("g")[0])
80+
param_l = float(mod.getParameters("l")[0])
8181
assert mod.getLinearInputs() == ["u1", "u2"]
8282
assert mod.getLinearStates() == ["omega", "phi"]
8383
assert mod.getLinearOutputs() == ["y1", "y2"]
84-
assert np.isclose(A, [[0, g/l], [1, 0]]).all()
84+
assert np.isclose(A, [[0, param_g / param_l], [1, 0]]).all()
8585
assert np.isclose(B, [[0, 0], [0, 1]]).all()
8686
assert np.isclose(C, [[0.5, 1], [0, 1]]).all()
8787
assert np.isclose(D, [[1, 0], [1, 0]]).all()

tests/test_typedParser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from OMPython import OMTypedParser
22

3-
typeCheck = OMTypedParser.parseString
3+
typeCheck = OMTypedParser.om_parser_typed
44

55

66
def test_newline_behaviour():

0 commit comments

Comments
 (0)