Skip to content

Commit

Permalink
Improved format strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
lextm committed Mar 15, 2024
1 parent b67f586 commit ee23c15
Show file tree
Hide file tree
Showing 33 changed files with 214 additions and 405 deletions.
2 changes: 1 addition & 1 deletion docs/source/docs/api-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ This example showcases some of its features:
# store compiled MIBs by calling this function
def store_mibs(mibName, jsonDoc, cbCtx):
print('# MIB module %s' % mibName)
print(f'# MIB module {mibName}')
print(jsonDoc)
mibCompiler = MibCompiler(
Expand Down
2 changes: 1 addition & 1 deletion examples/always-borrow-precompiled-pysnmp-files.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,4 @@
# run MIB compilation
results = mibCompiler.compile(*inputMibs)

print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results]))
print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}")
2 changes: 1 addition & 1 deletion examples/borrow-precompiled-pysnmp-files-on-failure.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,4 @@
# run non-recursive MIB compilation
results = mibCompiler.compile(*inputMibs)

print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results]))
print("Results: {', '.join(f'{x}:{results[x]}' for x in results}")
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@
# run [possibly recursive] MIB compilation
results = mibCompiler.compile(*inputMibs) # , rebuild=True, genTexts=True)

print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results]))
print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}")
2 changes: 1 addition & 1 deletion examples/compile-smiv2-mibs-from-text-into-pysnmp-code.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@
# run non-recursive MIB compilation
results = mibCompiler.compile(*inputMibs, **dict(noDeps=True))

print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results]))
print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}")
5 changes: 3 additions & 2 deletions examples/download-and-compile-smistar-mibs-into-json.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from pysmi.parser import SmiStarParser
from pysmi.codegen import JsonCodeGen
from pysmi.compiler import MibCompiler
import os

# from pysmi import debug

Expand All @@ -25,7 +26,7 @@


def printOut(mibName, jsonDoc, cbCtx):
print("\n\n# MIB module %s" % mibName)
print(f"{os.linesep}{os.linesep}# MIB module {mibName}")
print(jsonDoc)


Expand All @@ -45,4 +46,4 @@ def printOut(mibName, jsonDoc, cbCtx):
# run recursive MIB compilation
results = mibCompiler.compile(*inputMibs)

print("\n# Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results]))
print(f"{os.linesep}# Results: {'', ''.join(f'{x}:{results[x]}' for x in results)}")
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,4 @@
# run non-recursive MIB compilation
results = mibCompiler.compile(*inputMibs, **dict(noDeps=True))

print("Results: %s" % ", ".join([f"{x}:{results[x]}" for x in results]))
print(f"Results: {', '.join(f'{x}:{results[x]}' for x in results)}")
4 changes: 1 addition & 3 deletions pysmi/borrower/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ def __init__(self, reader, genTexts=False):
self._reader = reader

def __str__(self):
return "{}{{{}, genTexts={}, exts={}}}".format(
self.__class__.__name__, self._reader, self.genTexts, self.exts
)
return f"{self.__class__.__name__}{{{self._reader}, genTexts={self.genTexts}, exts={self.exts}}}"

def setOptions(self, **kwargs):
self._reader.setOptions(**kwargs)
Expand Down
28 changes: 13 additions & 15 deletions pysmi/codegen/intermediate.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def regSym(
moduleCompliance=False,
):
if symbol in self._seenSyms and symbol not in self._importMap:
raise error.PySmiSemanticError("Duplicate symbol found: %s" % symbol)
raise error.PySmiSemanticError(f"Duplicate symbol found: {symbol}")

self.addToExports(symbol, moduleIdentity)
self._out[symbol] = outDict
Expand Down Expand Up @@ -202,9 +202,9 @@ def genNumericOid(self, oid):
continue

if module not in self.symbolTable:
# XXX do getname for possible future borrowed mibs
# TODO: do getname for possible future borrowed mibs
raise error.PySmiSemanticError(
'no module "%s" in symbolTable' % module
f'no module "{module}" in symbolTable'
)

if parent not in self.symbolTable[module]:
Expand All @@ -222,7 +222,7 @@ def genNumericOid(self, oid):

def getBaseType(self, symName, module):
if module not in self.symbolTable:
raise error.PySmiSemanticError('no module "%s" in symbolTable' % module)
raise error.PySmiSemanticError(f'no module "{module}" in symbolTable')

if symName not in self.symbolTable[module]:
raise error.PySmiSemanticError(
Expand All @@ -233,7 +233,7 @@ def getBaseType(self, symName, module):
"syntax", (("", ""), "")
)
if not symType[0]:
raise error.PySmiSemanticError('unknown type for symbol "%s"' % symName)
raise error.PySmiSemanticError(f'unknown type for symbol "{symName}"')

if symType[0] in self.baseTypes:
return symType, symSubtype
Expand Down Expand Up @@ -767,8 +767,7 @@ def genDefVal(self, data, objname=None):

else:
raise error.PySmiSemanticError(
'unknown type "%s" for defval "%s" of symbol "%s"'
% (defvalType, defval, objname)
f'unknown type "{defvalType}" for defval "{defval}" of symbol "{objname}"'
)

return {"default": outDict}
Expand Down Expand Up @@ -866,7 +865,7 @@ def genOid(self, data):
out += (el[1],) # XXX Do we need to create a new object el[0]?

else:
raise error.PySmiSemanticError("unknown datatype for OID: %s" % el)
raise error.PySmiSemanticError(f"unknown datatype for OID: {el}")

return ".".join([str(x) for x in self.genNumericOid(out)]), parent

Expand All @@ -885,17 +884,17 @@ def genTime(self, data):
if len(timeStr) == 11:
timeStr = "19" + timeStr

# XXX raise in strict mode
# TODO: raise in strict mode
# elif lenTimeStr != 13:
# raise error.PySmiSemanticError("Invalid date %s" % t)
# raise error.PySmiSemanticError(f"Invalid date {t}")
try:
times.append(
strftime("%Y-%m-%d %H:%M", strptime(timeStr, "%Y%m%d%H%MZ"))
)

except ValueError:
# XXX raise in strict mode
# raise error.PySmiSemanticError("Invalid date %s: %s" % (t, sys.exc_info()[1]))
# TODO: raise in strict mode
# raise error.PySmiSemanticError(f"Invalid date {t}")
timeStr = "197001010000Z" # dummy date for dates with typos
times.append(
strftime("%Y-%m-%d %H:%M", strptime(timeStr, "%Y%m%d%H%MZ"))
Expand Down Expand Up @@ -1068,7 +1067,7 @@ def genCode(self, ast, symbolTable, **kwargs):
true_sym = sym[len(RESERVED_KEYWORDS_PREFIX) :]

if true_sym not in self._out:
raise error.PySmiCodegenError("No generated code for symbol %s" % sym)
raise error.PySmiCodegenError(f"No generated code for symbol {sym}")

outDict[sym] = self._out[true_sym]

Expand All @@ -1079,8 +1078,7 @@ def genCode(self, ast, symbolTable, **kwargs):
outDict["meta"]["comments"] = kwargs["comments"]

debug.logger & debug.flagCodegen and debug.logger(
"canonical MIB name %s (%s), imported MIB(s) %s"
% (self.moduleName[0], moduleOid, ",".join(importedModules) or "<none>")
f"canonical MIB name {self.moduleName[0]} ({moduleOid}), imported MIB(s) {','.join(importedModules) or '<none>'}"
)

return (
Expand Down
18 changes: 4 additions & 14 deletions pysmi/codegen/jsondoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,10 @@ def genCode(self, ast, symbolTable, **kwargs):

except jinja2.exceptions.TemplateError:
err = sys.exc_info()[1]
raise error.PySmiCodegenError("Jinja template rendering error: %s" % err)
raise error.PySmiCodegenError(f"Jinja template rendering error: {err}")

debug.logger & debug.flagCodegen and debug.logger(
"canonical MIB name %s (%s), imported MIB(s) %s, rendered from "
"%s, JSON document size %d bytes"
% (
mibInfo.name,
mibInfo.identity,
",".join(mibInfo.imported) or "<none>",
dstTemplate,
len(text),
)
f"canonical MIB name {mibInfo.name} ({mibInfo.identity}), imported MIB(s) {','.join(mibInfo.imported) or '<none>'}, rendered from {dstTemplate}, JSON document size {len(text)} bytes"
)

return mibInfo, text
Expand All @@ -90,9 +82,7 @@ def genIndex(self, processed, **kwargs):
outDict.update(json.loads(kwargs["old_index_data"]))

except Exception:
raise error.PySmiCodegenError(
"Index load error: %s" % sys.exc_info()[1]
)
raise error.PySmiCodegenError(f"Index load error: {sys.exc_info()[1]}")

def order(top):
if isinstance(top, dict):
Expand Down Expand Up @@ -165,7 +155,7 @@ def order(top):
outDict["meta"]["comments"] = kwargs["comments"]

debug.logger & debug.flagCodegen and debug.logger(
"OID->MIB index built, %s entries" % len(processed)
f"OID->MIB index built, {len(processed)} entries"
)

return json.dumps(order(outDict), indent=2)
2 changes: 1 addition & 1 deletion pysmi/codegen/null.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class NullCodeGen(AbstractCodeGen):

def genCode(self, ast, symbolTable, **kwargs):
debug.logger & debug.flagCodegen and debug.logger(
"%s invoked" % self.__class__.__name__
f"{self.__class__.__name__} invoked"
)
return MibInfo(oid=None, name="", imported=[]), ""

Expand Down
12 changes: 2 additions & 10 deletions pysmi/codegen/pysnmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,18 +153,10 @@ def translateOids(dct):

except jinja2.exceptions.TemplateError:
err = sys.exc_info()[1]
raise error.PySmiCodegenError("Jinja template rendering error: %s" % err)
raise error.PySmiCodegenError(f"Jinja template rendering error: {err}")

debug.logger & debug.flagCodegen and debug.logger(
"canonical MIB name %s (%s), imported MIB(s) %s, rendered from "
"%s, Python code size %d bytes"
% (
mibInfo.name,
mibInfo.identity,
",".join(mibInfo.imported) or "<none>",
dstTemplate,
len(text),
)
f"canonical MIB name {mibInfo.name} ({mibInfo.identity}), imported MIB(s) {','.join(mibInfo.imported) or '<none>'}, rendered from {dstTemplate}, Python code size {len(text)} bytes"
)

return mibInfo, text
Expand Down
15 changes: 5 additions & 10 deletions pysmi/codegen/symtable.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def regSym(self, symbol, symProps, parents=()):
if (
symbol in self._out or symbol in self._postponedSyms
): # add to strict mode - or symbol in self._importMap:
raise error.PySmiSemanticError("Duplicate symbol found: %s" % symbol)
raise error.PySmiSemanticError(f"Duplicate symbol found: {symbol}")

if self.allParentsExists(parents):
self._out[symbol] = symProps
Expand Down Expand Up @@ -506,7 +506,7 @@ def genOid(self, data, classmode=False):
out += (el[1],) # XXX Do we need to create a new object el[0]?

else:
raise error.PySmiSemanticError("unknown datatype for OID: %s" % el)
raise error.PySmiSemanticError(f"unknown datatype for OID: {el}")

return out

Expand Down Expand Up @@ -644,24 +644,19 @@ def genCode(self, ast, symbolTable, **kwargs):

if self._postponedSyms:
raise error.PySmiSemanticError(
"Unknown parents for symbols: %s" % ", ".join(self._postponedSyms)
f"Unknown parents for symbols: {', '.join(self._postponedSyms)}"
)

for sym in self._parentOids:
if sym not in self._out and sym not in self._importMap:
raise error.PySmiSemanticError("Unknown parent symbol: %s" % sym)
raise error.PySmiSemanticError(f"Unknown parent symbol: {sym}")

self._out["_symtable_order"] = list(self._symsOrder)
self._out["_symtable_cols"] = list(self._cols)
self._out["_symtable_rows"] = list(self._rows)

debug.logger & debug.flagCodegen and debug.logger(
"canonical MIB name {} ({}), imported MIB(s) {}, Symbol table size {} symbols".format(
self.moduleName[0],
moduleOid,
",".join(importedModules) or "<none>",
len(self._out),
)
f"canonical MIB name {self.moduleName[0]} ({moduleOid}), imported MIB(s) {','.join(importedModules) or '<none>'}, Symbol table size {len(self._out)} symbols"
)

return (
Expand Down
Loading

0 comments on commit ee23c15

Please sign in to comment.