Skip to content

Commit

Permalink
Convert all text strings to f-strings
Browse files Browse the repository at this point in the history
Reformats all the text from the old "%-formatted" and .format(...) format to the newer f-string format, as defined in PEP 498. This Requires Python 3.6+.

Flynt 0.69 was used to reformat the strings. 16 f-strings were created in 10 files.

F-strings are in general more readable, concise and performant. See also: https://www.python.org/dev/peps/pep-0498/#rationale
  • Loading branch information
EwoutH authored and tpike3 committed Dec 9, 2021
1 parent 5b591d2 commit d224397
Show file tree
Hide file tree
Showing 10 changed files with 16 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def network_portrayal(G):
"color": "#CC0000" if not agents or agents[0].wealth == 0 else "#007959",
"label": None
if not agents
else "Agent:{} Wealth:{}".format(agents[0].unique_id, agents[0].wealth),
else f"Agent:{agents[0].unique_id} Wealth:{agents[0].wealth}",
}
for (node_id, agents) in G.nodes.data("agent")
]
Expand Down
2 changes: 1 addition & 1 deletion examples/shape_example/shape_example/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def make_walker_agents(self):
heading = self.random.choice(self.headings)
# heading = (1, 0)
if self.grid.is_cell_empty(pos):
print("Creating agent {2} at ({0}, {1})".format(x, y, unique_id))
print(f"Creating agent {unique_id} at ({x}, {y})")
a = Walker(unique_id, self, pos, heading)
self.schedule.add(a)
self.grid.place_agent(a, pos)
Expand Down
2 changes: 1 addition & 1 deletion examples/shape_example/shape_example/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def agent_draw(agent):
# aesthetics
pass
elif isinstance(agent, Walker):
print("Uid: {0}, Heading: {1}".format(agent.unique_id, agent.heading))
print(f"Uid: {agent.unique_id}, Heading: {agent.heading}")
portrayal = {
"Shape": "arrowHead",
"Filled": "true",
Expand Down
6 changes: 2 additions & 4 deletions examples/virus_on_network/virus_on_network/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ def get_agents(source, target):
{
"size": 6,
"color": node_color(agents[0]),
"tooltip": "id: {}<br>state: {}".format(
agents[0].unique_id, agents[0].state.name
),
"tooltip": f"id: {agents[0].unique_id}<br>state: {agents[0].state.name}",
}
for (_, agents) in G.nodes.data("agent")
]
Expand Down Expand Up @@ -67,7 +65,7 @@ def get_agents(source, target):
class MyTextElement(TextElement):
def render(self, model):
ratio = model.resistant_susceptible_ratio()
ratio_text = "&infin;" if ratio is math.inf else "{0:.2f}".format(ratio)
ratio_text = "&infin;" if ratio is math.inf else f"{ratio:.2f}"
infected_text = str(number_infected(model))

return "Resistant/Susceptible Ratio: {}<br>Infected Remaining: {}".format(
Expand Down
2 changes: 1 addition & 1 deletion mesa/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@
__title__ = "mesa"
__version__ = "0.8.9"
__license__ = "Apache 2.0"
__copyright__ = "Copyright %s Project Mesa Team" % datetime.date.today().year
__copyright__ = f"Copyright {datetime.date.today().year} Project Mesa Team"
2 changes: 1 addition & 1 deletion mesa/batchrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ def __init__(self, model_cls, nr_processes=None, **kwargs):
# identify the number of processors available on users machine
available_processors = cpu_count()
self.processes = available_processors
print("BatchRunner MP will use {} processors.".format(self.processes))
print(f"BatchRunner MP will use {self.processes} processors.")
else:
self.processes = nr_processes

Expand Down
4 changes: 2 additions & 2 deletions mesa/visualization/ModularVisualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,8 @@ def launch(self, port=None, open_browser=True):
"""Run the app."""
if port is not None:
self.port = port
url = "http://127.0.0.1:{PORT}".format(PORT=self.port)
print("Interface starting at {url}".format(url=url))
url = f"http://127.0.0.1:{self.port}"
print(f"Interface starting at {url}")
self.listen(self.port)
if open_browser:
webbrowser.open(url)
Expand Down
2 changes: 1 addition & 1 deletion mesa/visualization/UserParam.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def __init__(
description=None,
):
if param_type not in self.TYPES:
raise ValueError("{} is not a valid Option type".format(param_type))
raise ValueError(f"{param_type} is not a valid Option type")
self.param_type = param_type
self.name = name
self._value = value
Expand Down
6 changes: 2 additions & 4 deletions mesa/visualization/modules/NetworkVisualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __init__(
library_types = ["sigma", "d3"]
if library not in library_types:
raise ValueError(
"Invalid javascript library type. Expected one of: %s" % library_types
f"Invalid javascript library type. Expected one of: {library_types}"
)

NetworkModule.package_includes = (
Expand All @@ -29,9 +29,7 @@ def __init__(
self.portrayal_method = portrayal_method
self.canvas_height = canvas_height
self.canvas_width = canvas_width
new_element = "new NetworkModule({}, {})".format(
self.canvas_width, self.canvas_height
)
new_element = f"new NetworkModule({self.canvas_width}, {self.canvas_height})"
self.js_code = "elements.push(" + new_element + ");"

def render(self, model):
Expand Down
10 changes: 4 additions & 6 deletions tests/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ def test_examples(self):
for example in os.listdir(self.EXAMPLES):
if not os.path.isdir(os.path.join(self.EXAMPLES, example)):
continue
if hasattr(self, "test_{}".format(example.replace("-", "_"))):
if hasattr(self, f"test_{example.replace('-', '_')}"):
# non-standard example; tested below
continue

print("testing example {!r}".format(example))
print(f"testing example {example!r}")
with self.active_example_dir(example):
try:
# model.py at the top level
Expand All @@ -55,11 +55,9 @@ def test_examples(self):
server.server.render_model()
except ImportError:
# <example>/model.py
mod = importlib.import_module(
"{}.model".format(example.replace("-", "_"))
)
mod = importlib.import_module(f"{example.replace('-', '_')}.model")
server = importlib.import_module(
"{}.server".format(example.replace("-", "_"))
f"{example.replace('-', '_')}.server"
)
server.server.render_model()
Model = getattr(mod, classcase(example))
Expand Down

0 comments on commit d224397

Please sign in to comment.