Skip to content

Commit

Permalink
Merge pull request #2228 from opentensor/feat/roman/enhance-switch-fr…
Browse files Browse the repository at this point in the history
…om-format-to-f-strings

Enhance: Switch from format() to f-strings
  • Loading branch information
roman-opentensor authored Aug 13, 2024
2 parents 91017a7 + b0bc7ad commit 38bbf7b
Show file tree
Hide file tree
Showing 18 changed files with 71 additions and 121 deletions.
22 changes: 6 additions & 16 deletions bittensor/core/axon.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,23 +550,17 @@ async def endpoint(*args, **kwargs):
)
assert (
signature(blacklist_fn) == blacklist_sig
), "The blacklist_fn function must have the signature: blacklist( synapse: {} ) -> Tuple[bool, str]".format(
request_name
)
), f"The blacklist_fn function must have the signature: blacklist( synapse: {request_name} ) -> Tuple[bool, str]"
if priority_fn:
priority_sig = Signature(expected_params, return_annotation=float)
assert (
signature(priority_fn) == priority_sig
), "The priority_fn function must have the signature: priority( synapse: {} ) -> float".format(
request_name
)
), f"The priority_fn function must have the signature: priority( synapse: {request_name} ) -> float"
if verify_fn:
verify_sig = Signature(expected_params, return_annotation=None)
assert (
signature(verify_fn) == verify_sig
), "The verify_fn function must have the signature: verify( synapse: {} ) -> None".format(
request_name
)
), f"The verify_fn function must have the signature: verify( synapse: {request_name} ) -> None"

# Store functions in appropriate attribute dictionaries
self.forward_class_types[request_name] = param_class
Expand Down Expand Up @@ -730,13 +724,9 @@ def to_string(self):

def __str__(self) -> str:
"""Provides a human-readable representation of the Axon instance."""
return "Axon({}, {}, {}, {}, {})".format(
self.ip,
self.port,
self.wallet.hotkey.ss58_address,
"started" if self.started else "stopped",
list(self.forward_fns.keys()),
)
_started = "started" if self.started else "stopped"
_keys = list(self.forward_fns.keys())
return f"Axon({self.ip}, {self.port}, {self.wallet.hotkey.ss58_address}, {_started}, {_keys})"

def __repr__(self) -> str:
"""
Expand Down
4 changes: 1 addition & 3 deletions bittensor/core/chain_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,7 @@ def __eq__(self, other: "AxonInfo"):
return False

def __str__(self):
return "AxonInfo( {}, {}, {}, {} )".format(
str(self.ip_str()), str(self.hotkey), str(self.coldkey), self.version
)
return f"AxonInfo( {self.ip_str()}, {self.hotkey}, {self.coldkey}, {self.version} )"

def __repr__(self):
return self.__str__()
Expand Down
4 changes: 2 additions & 2 deletions bittensor/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ def __init__(
try:
with open(config_file_path) as f:
params_config = yaml.safe_load(f)
print("Loading config defaults from: {}".format(config_file_path))
print(f"Loading config defaults from: {config_file_path}")
parser.set_defaults(**params_config)
except Exception as e:
print("Error in loading: {} using default parser settings".format(e))
print(f"Error in loading: {e} using default parser settings")

# 2. Continue with loading in params.
params = config.__parse_args__(args=args, parser=parser, strict=strict)
Expand Down
2 changes: 1 addition & 1 deletion bittensor/core/dendrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,7 @@ def __str__(self) -> str:
Returns:
str: The string representation of the Dendrite object in the format :func:`dendrite(<user_wallet_address>)`.
"""
return "dendrite({})".format(self.keypair.ss58_address)
return f"dendrite({self.keypair.ss58_address})"

def __repr__(self) -> str:
"""
Expand Down
4 changes: 1 addition & 3 deletions bittensor/core/metagraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,9 +407,7 @@ def __str__(self) -> str:
print(metagraph) # Output: "metagraph(netuid:1, n:100, block:500, network:finney)"
"""
return "metagraph(netuid:{}, n:{}, block:{}, network:{})".format(
self.netuid, self.n.item(), self.block.item(), self.network
)
return f"metagraph(netuid:{self.netuid}, n:{self.n.item()}, block:{self.block.item()}, network:{self.network})"

def __repr__(self) -> str:
"""
Expand Down
12 changes: 4 additions & 8 deletions bittensor/core/subtensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,10 @@ def __init__(
def __str__(self) -> str:
if self.network == self.chain_endpoint:
# Connecting to chain endpoint without network known.
return "subtensor({})".format(self.chain_endpoint)
return f"subtensor({self.chain_endpoint})"
else:
# Connecting to network with endpoint known.
return "subtensor({}, {})".format(self.network, self.chain_endpoint)
return f"subtensor({self.network}, {self.chain_endpoint})"

def __repr__(self) -> str:
return self.__str__()
Expand Down Expand Up @@ -1802,9 +1802,7 @@ def get_transfer_fee(
)
except Exception as e:
settings.bt_console.print(
":cross_mark: [red]Failed to get payment info[/red]:[bold white]\n {}[/bold white]".format(
e
)
f":cross_mark: [red]Failed to get payment info[/red]:[bold white]\n {e}[/bold white]"
)
payment_info = {"partialFee": int(2e7)} # assume 0.02 Tao

Expand Down Expand Up @@ -1883,9 +1881,7 @@ def commit_weights(
message = "No attempt made. Perhaps it is too soon to commit weights!"

logging.info(
"Committing weights with params: netuid={}, uids={}, weights={}, version_key={}".format(
netuid, uids, weights, version_key
)
f"Committing weights with params: netuid={netuid}, uids={uids}, weights={weights}, version_key={version_key}"
)

# Generate the hash of the weights
Expand Down
10 changes: 5 additions & 5 deletions bittensor/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def get_explorer_root_url_by_network_from_map(

def get_explorer_url_for_network(
network: str, block_hash: str, network_map: Dict[str, str]
) -> Optional[List[str]]:
) -> Optional[Dict[str, str]]:
"""
Returns the explorer url for the given block hash and network.
Expand All @@ -195,11 +195,11 @@ def get_explorer_url_for_network(

if explorer_root_urls != {}:
# We are on a known network.
explorer_opentensor_url = "{root_url}/query/{block_hash}".format(
root_url=explorer_root_urls.get("opentensor"), block_hash=block_hash
explorer_opentensor_url = (
f"{explorer_root_urls.get('opentensor')}/query/{block_hash}"
)
explorer_taostats_url = "{root_url}/extrinsic/{block_hash}".format(
root_url=explorer_root_urls.get("taostats"), block_hash=block_hash
explorer_taostats_url = (
f"{explorer_root_urls.get('taostats')}/extrinsic/{block_hash}"
)
explorer_urls["opentensor"] = explorer_opentensor_url
explorer_urls["taostats"] = explorer_taostats_url
Expand Down
7 changes: 2 additions & 5 deletions bittensor/utils/balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,8 @@ def __str__(self):
return f"{self.unit}{float(self.tao):,.9f}"

def __rich__(self):
return "[green]{}[/green][green]{}[/green][green].[/green][dim green]{}[/dim green]".format(
self.unit,
format(float(self.tao), "f").split(".")[0],
format(float(self.tao), "f").split(".")[1],
)
int_tao, fract_tao = format(float(self.tao), "f").split(".")
return f"[green]{self.unit}[/green][green]{int_tao}[/green][green].[/green][dim green]{fract_tao}[/dim green]"

def __str_rao__(self):
return f"{self.rao_unit}{int(self.rao)}"
Expand Down
4 changes: 2 additions & 2 deletions bittensor/utils/btlogging/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def formatTime(self, record, datefmt=None) -> str:
s = time.strftime(datefmt, created)
else:
s = time.strftime("%Y-%m-%d %H:%M:%S", created)
s += ".{:03d}".format(int(record.msecs))
s += f".{int(record.msecs):03d}"
return s

def format(self, record) -> str:
Expand Down Expand Up @@ -205,7 +205,7 @@ def formatTime(self, record, datefmt=None) -> str:
s = time.strftime(datefmt, created)
else:
s = time.strftime("%Y-%m-%d %H:%M:%S", created)
s += ".{:03d}".format(int(record.msecs))
s += f".{int(record.msecs):03d}"
return s

def format(self, record) -> str:
Expand Down
33 changes: 11 additions & 22 deletions bittensor/utils/deprecated/extrinsics/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,13 @@ def prometheus_extrinsic(
try:
external_ip = net.get_external_ip()
bt_console.print(
":white_heavy_check_mark: [green]Found external ip: {}[/green]".format(
external_ip
)
)
logging.success(
prefix="External IP", suffix="<blue>{}</blue>".format(external_ip)
f":white_heavy_check_mark: [green]Found external ip: {external_ip}[/green]"
)
except Exception as E:
logging.success(prefix="External IP", suffix="<blue>{external_ip}</blue>")
except Exception as e:
raise RuntimeError(
"Unable to attain your external ip. Check your internet connection. error: {}".format(
E
)
) from E
f"Unable to attain your external ip. Check your internet connection. error: {e}"
) from e
else:
external_ip = ip

Expand Down Expand Up @@ -105,21 +99,17 @@ def prometheus_extrinsic(
)

bt_console.print(
":white_heavy_check_mark: [white]Prometheus already served.[/white]".format(
external_ip
)
f":white_heavy_check_mark: [white]Prometheus already served.[/white]"
)
return True

# Add netuid, not in prometheus_info
call_params["netuid"] = netuid

with bt_console.status(
":satellite: Serving prometheus on: [white]{}:{}[/white] ...".format(
subtensor.network, netuid
)
f":satellite: Serving prometheus on: [white]{subtensor.network}:{netuid}[/white] ..."
):
success, err = subtensor.do_serve_prometheus(
success, error_message = subtensor.do_serve_prometheus(
wallet=wallet,
call_params=call_params,
wait_for_finalization=wait_for_finalization,
Expand All @@ -128,14 +118,13 @@ def prometheus_extrinsic(

if wait_for_inclusion or wait_for_finalization:
if success is True:
json_ = json.dumps(call_params, indent=4, sort_keys=True)
bt_console.print(
":white_heavy_check_mark: [green]Served prometheus[/green]\n [bold white]{}[/bold white]".format(
json.dumps(call_params, indent=4, sort_keys=True)
)
f":white_heavy_check_mark: [green]Served prometheus[/green]\n [bold white]{json_}[/bold white]"
)
return True
else:
bt_console.print(f":cross_mark: [red]Failed[/red]: {err}")
bt_console.print(f":cross_mark: [red]Failed[/red]: {error_message}")
return False
else:
return True
20 changes: 6 additions & 14 deletions bittensor/utils/deprecated/extrinsics/serving.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,7 @@ def serve_extrinsic(
output["coldkey"] = wallet.coldkeypub.ss58_address
output["hotkey"] = wallet.hotkey.ss58_address
if not Confirm.ask(
"Do you want to serve axon:\n [bold white]{}[/bold white]".format(
json.dumps(output, indent=4, sort_keys=True)
)
f"Do you want to serve axon:\n [bold white]{json.dumps(output, indent=4, sort_keys=True)}[/bold white]"
):
return False

Expand Down Expand Up @@ -168,19 +166,13 @@ def serve_axon_extrinsic(
try:
external_ip = net.get_external_ip()
bt_console.print(
":white_heavy_check_mark: [green]Found external ip: {}[/green]".format(
external_ip
)
)
logging.success(
prefix="External IP", suffix="<blue>{}</blue>".format(external_ip)
f":white_heavy_check_mark: [green]Found external ip: {external_ip}[/green]"
)
except Exception as E:
logging.success(prefix="External IP", suffix=f"<blue>{external_ip}</blue>")
except Exception as e:
raise RuntimeError(
"Unable to attain your external ip. Check your internet connection. error: {}".format(
E
)
) from E
f"Unable to attain your external ip. Check your internet connection. error: {e}"
) from e
else:
external_ip = axon.external_ip

Expand Down
12 changes: 6 additions & 6 deletions bittensor/utils/deprecated/extrinsics/set_weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,13 @@ def set_weights_extrinsic(
# Ask before moving on.
if prompt:
if not Confirm.ask(
"Do you want to set weights:\n[bold white] weights: {}\n uids: {}[/bold white ]?".format(
[float(v / 65535) for v in weight_vals], weight_uids
)
f"Do you want to set weights:\n[bold white] weights: {[float(v / 65535) for v in weight_vals]}\n"
f"uids: {weight_uids}[/bold white ]?"
):
return False, "Prompt refused."

with bt_console.status(
":satellite: Setting weights on [white]{}[/white] ...".format(subtensor.network)
f":satellite: Setting weights on [white]{subtensor.network}[/white] ..."
):
try:
success, error_message = subtensor.do_set_weights(
Expand All @@ -107,8 +106,9 @@ def set_weights_extrinsic(
if success is True:
bt_console.print(":white_heavy_check_mark: [green]Finalized[/green]")
logging.success(
msg=str(success),
prefix="Set weights",
suffix="<green>Finalized: </green>" + str(success),
suffix="<green>Finalized: </green>",
)
return True, "Successfully set weights and Finalized."
else:
Expand All @@ -120,7 +120,7 @@ def set_weights_extrinsic(
return False, error_message

except Exception as e:
bt_console.print(":cross_mark: [red]Failed[/red]: error:{}".format(e))
bt_console.print(f":cross_mark: [red]Failed[/red]: error:{e}")
logging.warning(
msg=str(e), prefix="Set weights", suffix="<red>Failed: </red>"
)
Expand Down
33 changes: 14 additions & 19 deletions bittensor/utils/deprecated/extrinsics/transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ def transfer_extrinsic(
# Validate destination address.
if not is_valid_bittensor_address_or_public_key(dest):
bt_console.print(
":cross_mark: [red]Invalid destination address[/red]:[bold white]\n {}[/bold white]".format(
dest
)
f":cross_mark: [red]Invalid destination address[/red]:[bold white]\n {dest}[/bold white]"
)
return False

Expand Down Expand Up @@ -96,18 +94,21 @@ def transfer_extrinsic(
# Check if we have enough balance.
if account_balance < (transfer_balance + fee + existential_deposit):
bt_console.print(
":cross_mark: [red]Not enough balance[/red]:[bold white]\n balance: {}\n amount: {}\n for fee: {}[/bold white]".format(
account_balance, transfer_balance, fee
)
":cross_mark: [red]Not enough balance[/red]:[bold white]\n"
f" balance: {account_balance}\n"
f" amount: {transfer_balance}\n"
f" for fee: {fee}[/bold white]"
)
return False

# Ask before moving on.
if prompt:
if not Confirm.ask(
"Do you want to transfer:[bold white]\n amount: {}\n from: {}:{}\n to: {}\n for fee: {}[/bold white]".format(
transfer_balance, wallet.name, wallet.coldkey.ss58_address, dest, fee
)
"Do you want to transfer:[bold white]\n"
f" amount: {transfer_balance}\n"
f" from: {wallet.name}:{wallet.coldkey.ss58_address}\n"
f" to: {dest}\n"
f" for fee: {fee}[/bold white]"
):
return False

Expand All @@ -122,21 +123,17 @@ def transfer_extrinsic(

if success:
bt_console.print(":white_heavy_check_mark: [green]Finalized[/green]")
bt_console.print("[green]Block Hash: {}[/green]".format(block_hash))
bt_console.print(f"[green]Block Hash: {block_hash}[/green]")

explorer_urls = get_explorer_url_for_network(
subtensor.network, block_hash, NETWORK_EXPLORER_MAP
)
if explorer_urls != {} and explorer_urls:
bt_console.print(
"[green]Opentensor Explorer Link: {}[/green]".format(
explorer_urls.get("opentensor")
)
f"[green]Opentensor Explorer Link: {explorer_urls.get('opentensor')}[/green]"
)
bt_console.print(
"[green]Taostats Explorer Link: {}[/green]".format(
explorer_urls.get("taostats")
)
f"[green]Taostats Explorer Link: {explorer_urls.get('taostats')}[/green]"
)
else:
bt_console.print(f":cross_mark: [red]Failed[/red]: {err_msg}")
Expand All @@ -145,9 +142,7 @@ def transfer_extrinsic(
with bt_console.status(":satellite: Checking Balance..."):
new_balance = subtensor.get_balance(wallet.coldkey.ss58_address)
bt_console.print(
"Balance:\n [blue]{}[/blue] :arrow_right: [green]{}[/green]".format(
account_balance, new_balance
)
f"Balance:\n [blue]{account_balance}[/blue] :arrow_right: [green]{new_balance}[/green]"
)
return True

Expand Down
Loading

0 comments on commit 38bbf7b

Please sign in to comment.