188 #
189 gids_from_top = list(reversed(range(1, ng + 1)))
190 gids_to_scan = gids_from_top[:-1][:4]
191 assert gids_from_top, ("Too few gear-ratios?", ng, gidx.gnames)192193 all_recs = []
194 ok_rec = None
195 for gid in gids_to_scan:
112 assert not (np.isnan(v_max) or np.isnan(n_v_max)), locals()
113 assert v_max == vround(v_max), (v_max, vround(v_max))
114 _i = wot.loc[roots_head[0] :, w.p_remain_stable].iteritems()
115 assert next(_i)[1] > 0 and next(_i)[1] <= 0, (116 "Solution is not the last positive p_remain:",117 roots_head[0],118 v_max,119 wot.loc[v_max - 5 * v_step : v_max + 5 * v_step, w.p_remain_stable],120 )121 rec = VMaxRec(v_max, n_v_max, gid, False, wot)
122 else:
123 rec = VMaxRec(np.NAN, np.NAN, gid, False, wot)
110 n_v_max = wot.loc[v_max, w.n]
111
112 assert not (np.isnan(v_max) or np.isnan(n_v_max)), locals()
113 assert v_max == vround(v_max), (v_max, vround(v_max))114 _i = wot.loc[roots_head[0] :, w.p_remain_stable].iteritems()
115 assert next(_i)[1] > 0 and next(_i)[1] <= 0, (
116 "Solution is not the last positive p_remain:",
109 v_max = roots_head[0] # Plain rounding, already close to grid.
110 n_v_max = wot.loc[v_max, w.n]
111
112 assert not (np.isnan(v_max) or np.isnan(n_v_max)), locals()113 assert v_max == vround(v_max), (v_max, vround(v_max))
114 _i = wot.loc[roots_head[0] :, w.p_remain_stable].iteritems()
115 assert next(_i)[1] > 0 and next(_i)[1] <= 0, (
79 v_max = wot.index[-1] # v @ max n
80 n_v_max = wot.loc[:, w.n].iloc[-1]
81
82 assert not (np.isnan(v_max) or np.isnan(n_v_max)), locals() 83 rec = VMaxRec(v_max, n_v_max, gid, True, wot)
84 else:
85 v_max = np.NAN
66 """
67 w = wio.pstep_factory.get().wot
68
69 assert not wot.empty 70 71 wot = wot.copy() # or else warn, when appending columns.
72
73 wot[w.p_resist] = p_resist
38@autog.autographed(needs=["wltc_data/classes", ..., ...])
39def decide_wltc_class(wltc_classes_data: Mapping[str, dict], p_m_ratio, v_max):
40 """Vehicle classification according to Annex 1-2. """
41 assert isinstance(p_m_ratio, (int, float)) and isinstance(v_max, (int, float)), locals() 42 43 c = wio.pstep_factory.get().cycle_data
44
45 class_limits = {
301 ):
302 if gnames is None:
303 gnames = self.gnames
304 assert gnames, locals()305306 if isinstance(item, str):
307 item = (item,)
308 return pd.MultiIndex.from_tuples(itt.product(item, gnames))
106 """Use :func:`flatten_columns()` to inverse it"""
107
108 def split_column_name(name):
109 assert isinstance(name, str), ("Inflating Multiindex?", columns)110 names = name.split(sep)
111 if len(names) < levels:
112 nlevels_missing = levels - len(names)
157 2 1
158 dtype: int8
159 """
160 assert isinstance(nan_val, int), nan_val161162 nan_rows = (df == NANFLAG).all(axis=1)
163 rows_to_or = df.loc[~nan_rows].replace(NANFLAG, nan_val).astype(bool)
164 (_, col0), *cols = rows_to_or.iteritems()
731 GEARS, CLUTCH.shape, driveability_issues
732 )
733 assert "i" == GEARS.dtype.kind, GEARS.dtype
734 assert ((GEARS >= -1) & (GEARS <= len(n2v_ratios))).all(), (min(GEARS), max(GEARS))735736 return (
737 GEARS,
738 CLUTCH,
730 assert GEARS.shape == CLUTCH.shape == driveability_issues.shape, _shapes(
731 GEARS, CLUTCH.shape, driveability_issues
732 )
733 assert "i" == GEARS.dtype.kind, GEARS.dtype734 assert ((GEARS >= -1) & (GEARS <= len(n2v_ratios))).all(), (min(GEARS), max(GEARS))
735
736 return (
727 CLUTCH[(GEARS == 2) & (_N_GEARS[1, :] < n_clutch_gear2)] = True
728
729 assert V.shape == GEARS.shape, _shapes(V, GEARS)
730 assert GEARS.shape == CLUTCH.shape == driveability_issues.shape, _shapes(731 GEARS, CLUTCH.shape, driveability_issues732 )733 assert "i" == GEARS.dtype.kind, GEARS.dtype
734 assert ((GEARS >= -1) & (GEARS <= len(n2v_ratios))).all(), (min(GEARS), max(GEARS))
735
726 GEARS = selectGears(_GEARS, _G_BY_N, _G_BY_P, driveability_issues)
727 CLUTCH[(GEARS == 2) & (_N_GEARS[1, :] < n_clutch_gear2)] = True
728
729 assert V.shape == GEARS.shape, _shapes(V, GEARS)730 assert GEARS.shape == CLUTCH.shape == driveability_issues.shape, _shapes(
731 GEARS, CLUTCH.shape, driveability_issues
732 )
719 driveability_issues,
720 )
721
722 assert (723 _GEAR_RATIOS.shape == _N_GEARS.shape == _P_AVAILS.shape == _N_NORMS.shape724 ), _shapes(_GEAR_RATIOS, _N_GEARS, _P_AVAILS, _N_NORMS)725726 GEARS = selectGears(_GEARS, _G_BY_N, _G_BY_P, driveability_issues)
727 CLUTCH[(GEARS == 2) & (_N_GEARS[1, :] < n_clutch_gear2)] = True
728
420
421
422def assert_regexp_unmatched(regex, string, msg):
423 assert not re.findall(regex, string), "%s: %s" % (424 msg,425 [(m.start(), m.group()) for m in re.finditer(regex, string)],426 )
427
428
414
415
416def bytes2np(bytesarr):
417 assert isinstance(bytesarr, bytes), "Not bytes: %s" % bytesarr418419 return np.frombuffer(bytesarr, dtype="uint8") - _escape_char
420
421
406
407def np2bytes(NUMS):
408 if (NUMS < 0).any() or (NUMS >= (256 - _escape_char)).any():
409 assert all(NUMS >= 0) and all(NUMS < (256 - _escape_char)), (410 "Outside byte-range: %s" % NUMS[(NUMS < 0) | (NUMS >= (256 - _escape_char))]411 )
412
413 return (NUMS + _escape_char).astype("uint8").tostring()
396 \g124|\g7 --> unicode(128+124=252)|unicode(128+7=135)
397 """
398
399 assert isinstance(gearspattern, bytes), (400 "Not bytes: %s" % gearspattern401 ) # For python-2 to work with __future__.unicode_literals.402403 regex = _regex_gears2regex.sub(dec_byte_repl, gearspattern)
404 return re.compile(regex)
405
277 sol = pipelines.cycler_pipeline().compute({**mdl, "V_compensated": V})
278 P_req = sol["cycle"]["P_req"]
279 idx = ~p_req.isnull()
280 assert (p_req[idx] == P_req[idx]).all()281282 ## Remaining n_max values283 #284 g_max_n2v = n2v_ratios[mdl[m.g_vmax] - 1]
285 # NOTE: `n95_high` is not rounded based on v, like the rest n_mins.
286 mdl[m.n_max1] = mdl[m.n95_high]
253 cb = cycler.CycleBuilder(V, V_target)
254 V = V_target
255
256 assert isinstance(V, pd.Series), V257258 pm = cycler.PhaseMarker()
259
260 if wltc_class:
238 assert mdl['pmr'] == sol['p_m_ratio']
239 # for i in "v_max g_vmax n_vmax wltc_class n95_high n95_low".split():
240 for i in "v_max g_vmax n_vmax wltc_class".split():
241 assert mdl[i] == sol[i]242
243 # TODO: separate column due to cap/extend.
244 V_target = V_dsc.copy()
235 orig_mdl.pop('v_max', None) # vehdb contains v_max!
236 sol = pipelines.scale_trace_pipeline().compute(orig_mdl)
237 assert (V_dsc == sol["V_dsc"]).all()
238 assert mdl['pmr'] == sol['p_m_ratio']239 # for i in "v_max g_vmax n_vmax wltc_class n95_high n95_low".split():240 for i in "v_max g_vmax n_vmax wltc_class".split():
241 assert mdl[i] == sol[i]
242
234 #
235 orig_mdl.pop('v_max', None) # vehdb contains v_max!
236 sol = pipelines.scale_trace_pipeline().compute(orig_mdl)
237 assert (V_dsc == sol["V_dsc"]).all()238 assert mdl['pmr'] == sol['p_m_ratio']
239 # for i in "v_max g_vmax n_vmax wltc_class n95_high n95_low".split():
240 for i in "v_max g_vmax n_vmax wltc_class".split():
195
196 class_data = datamodel.get_class(wltc_class, mdl=self._model)
197 V = datamodel.get_class_v_cycle(wltc_class)
198 assert isinstance(V, pd.Series), V199200 ## Downscale velocity-profile.201 #202 f_dsc = mdl.get(m.f_dsc)
203 if not f_dsc:
204 f_dsc_threshold = mdl[m.f_dsc_threshold]
Usage of assert
statement in application logic is discouraged. assert
is removed with compiling to optimized byte code. Consider raising an exception instead. Ideally, assert
statement should be used only in tests.
Python has an option to compile the optimized bytecode and create the respective .pyo
files by using the options -O
and -OO
. When used, these basic optimizations are done:
- All the assert statements are removed
- All docstrings are removed (when -OO is selected)
- Value of the
__debug__
built-in variable is set toFalse
It is recommended not to use assert
in non-test files. A better way for internal self-checks is to check explicitly and raise respective error using an if statement.
Tip: Make sure test_patterns
are defined in .deepsource.toml
to avoid false-positives. Please check the documentation to know more.
Consider this code snippet:
def read_secret(self):
assert self.is_admin, "You are unauthorized to read this"
return self._secret
If python
is run with the -O
flag, the check for self.is_admin
is
completely ignored, which can cause secrets to be leaked.
This is how you can ensure the code always works:
def read_secret(self):
if not self.is_admin:
raise AssertionError("You are unauthorized to read this")
return self._secret
Here's a more detailed example. Consider the following script foo.py
:
import sys
def run():
assert len(sys.argv) == 5 # Insecure, statement will be removed when compiled to optimized byte code
print("Argument variables are: ", sys.argv)
run()
When optimization is disabled:
$ python foo.py 1 2 3 4 5
Traceback (most recent call last):
File "foo.py", line 7, in <module>
run()
File "foo.py", line 4, in run
assert len(sys.argv) == 5 # Insecure, statement will be removed when compiled to optimized byte code
AssertionError
When optimization is enabled:
$ python -O foo.pyo 1 2 3 4 5 6
Argument variables are: ['foo.pyo', '1', '2', '3', '4', '5', '6']
Here, all the internal self-checks using the assert statements are removed, as we can see. Therefore, there's a chance for an application to behave strangely in this case. It is better do raise the Exception explicitly:
import sys
def run():
if not len(sys.argv) == 5:
raise ValueError
print("Argument variables are: ", sys.argv)
run()
Note: During autofix, DeepSource will change the assert
statements to if
statements raising AssertionError
.
This is done to replicate the existing behavior.
References:
- -O flag in python
- -OO flag in python
- Discuss blogpost - Using assert outside tests