diff --git a/bittensor/core/axon.py b/bittensor/core/axon.py index e5ae679d1..da1392f13 100644 --- a/bittensor/core/axon.py +++ b/bittensor/core/axon.py @@ -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 @@ -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: """ diff --git a/bittensor/core/chain_data.py b/bittensor/core/chain_data.py index e96dbd2ba..6d4e6103c 100644 --- a/bittensor/core/chain_data.py +++ b/bittensor/core/chain_data.py @@ -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__() diff --git a/bittensor/core/config.py b/bittensor/core/config.py index 79eda9c90..61afb5f05 100644 --- a/bittensor/core/config.py +++ b/bittensor/core/config.py @@ -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) diff --git a/bittensor/core/dendrite.py b/bittensor/core/dendrite.py index 3daeca3f2..c40c018bc 100644 --- a/bittensor/core/dendrite.py +++ b/bittensor/core/dendrite.py @@ -742,7 +742,7 @@ def __str__(self) -> str: Returns: str: The string representation of the Dendrite object in the format :func:`dendrite()`. """ - return "dendrite({})".format(self.keypair.ss58_address) + return f"dendrite({self.keypair.ss58_address})" def __repr__(self) -> str: """ diff --git a/bittensor/core/metagraph.py b/bittensor/core/metagraph.py index fdb46dcbe..8fee673ff 100644 --- a/bittensor/core/metagraph.py +++ b/bittensor/core/metagraph.py @@ -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: """ diff --git a/bittensor/core/subtensor.py b/bittensor/core/subtensor.py index 9b35cda2e..f50d449d7 100644 --- a/bittensor/core/subtensor.py +++ b/bittensor/core/subtensor.py @@ -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__() @@ -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 @@ -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 diff --git a/bittensor/utils/__init__.py b/bittensor/utils/__init__.py index e4be85346..3089aff70 100644 --- a/bittensor/utils/__init__.py +++ b/bittensor/utils/__init__.py @@ -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. @@ -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 diff --git a/bittensor/utils/balance.py b/bittensor/utils/balance.py index 90c851814..efe21885e 100644 --- a/bittensor/utils/balance.py +++ b/bittensor/utils/balance.py @@ -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)}" diff --git a/bittensor/utils/btlogging/format.py b/bittensor/utils/btlogging/format.py index 70629128f..131085f17 100644 --- a/bittensor/utils/btlogging/format.py +++ b/bittensor/utils/btlogging/format.py @@ -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: @@ -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: diff --git a/bittensor/utils/deprecated/extrinsics/prometheus.py b/bittensor/utils/deprecated/extrinsics/prometheus.py index 2dd668bda..64ee07c60 100644 --- a/bittensor/utils/deprecated/extrinsics/prometheus.py +++ b/bittensor/utils/deprecated/extrinsics/prometheus.py @@ -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="{}".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="{external_ip}") + 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 @@ -105,9 +99,7 @@ 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 @@ -115,11 +107,9 @@ def prometheus_extrinsic( 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, @@ -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 diff --git a/bittensor/utils/deprecated/extrinsics/serving.py b/bittensor/utils/deprecated/extrinsics/serving.py index ab2421566..7253f25d7 100644 --- a/bittensor/utils/deprecated/extrinsics/serving.py +++ b/bittensor/utils/deprecated/extrinsics/serving.py @@ -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 @@ -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="{}".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"{external_ip}") + 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 diff --git a/bittensor/utils/deprecated/extrinsics/set_weights.py b/bittensor/utils/deprecated/extrinsics/set_weights.py index 8848f38b6..15681dbb1 100644 --- a/bittensor/utils/deprecated/extrinsics/set_weights.py +++ b/bittensor/utils/deprecated/extrinsics/set_weights.py @@ -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( @@ -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="Finalized: " + str(success), + suffix="Finalized: ", ) return True, "Successfully set weights and Finalized." else: @@ -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="Failed: " ) diff --git a/bittensor/utils/deprecated/extrinsics/transfer.py b/bittensor/utils/deprecated/extrinsics/transfer.py index e56245895..7f7decccf 100644 --- a/bittensor/utils/deprecated/extrinsics/transfer.py +++ b/bittensor/utils/deprecated/extrinsics/transfer.py @@ -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 @@ -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 @@ -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}") @@ -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 diff --git a/bittensor/utils/networking.py b/bittensor/utils/networking.py index 66f397114..db1a0d7a6 100644 --- a/bittensor/utils/networking.py +++ b/bittensor/utils/networking.py @@ -164,6 +164,6 @@ def get_formatted_ws_endpoint_url(endpoint_url: str) -> str: The formatted endpoint url. In the form of ws:// or wss:// """ if endpoint_url[0:6] != "wss://" and endpoint_url[0:5] != "ws://": - endpoint_url = "ws://{}".format(endpoint_url) + endpoint_url = f"ws://{endpoint_url}" return endpoint_url diff --git a/bittensor/utils/version.py b/bittensor/utils/version.py index c79fb6492..f0ff70763 100644 --- a/bittensor/utils/version.py +++ b/bittensor/utils/version.py @@ -103,10 +103,9 @@ def check_version(timeout: int = 15): if Version(latest_version) > Version(__version__): print( - "\u001b[33mBittensor Version: Current {}/Latest {}\nPlease update to the latest version at your earliest convenience. " - "Run the following command to upgrade:\n\n\u001b[0mpython -m pip install --upgrade bittensor".format( - __version__, latest_version - ) + f"\u001b[33mBittensor Version: Current {__version__}/Latest {latest_version}\n" + f"Please update to the latest version at your earliest convenience. " + "Run the following command to upgrade:\n\n\u001b[0mpython -m pip install --upgrade bittensor" ) pass except Exception as e: diff --git a/bittensor/utils/weight_utils.py b/bittensor/utils/weight_utils.py index 5e5fa0b73..3cc56ac96 100644 --- a/bittensor/utils/weight_utils.py +++ b/bittensor/utils/weight_utils.py @@ -195,16 +195,12 @@ def convert_weights_and_uids_for_emit( weights = weights.tolist() uids = uids.tolist() if min(weights) < 0: - raise ValueError( - "Passed weight is negative cannot exist on chain {}".format(weights) - ) + raise ValueError(f"Passed weight is negative cannot exist on chain {weights}") if min(uids) < 0: - raise ValueError("Passed uid is negative cannot exist on chain {}".format(uids)) + raise ValueError(f"Passed uid is negative cannot exist on chain {uids}") if len(uids) != len(weights): raise ValueError( - "Passed weights and uids must have the same length, got {} and {}".format( - len(uids), len(weights) - ) + f"Passed weights and uids must have the same length, got {len(uids)} and {len(weights)}" ) if sum(weights) == 0: return [], [] # Nothing to set on chain. diff --git a/tests/e2e_tests/utils/test_utils.py b/tests/e2e_tests/utils/test_utils.py index 9061df791..73838b3a2 100644 --- a/tests/e2e_tests/utils/test_utils.py +++ b/tests/e2e_tests/utils/test_utils.py @@ -25,7 +25,7 @@ def setup_wallet(uri: str) -> Tuple[Keypair, bittensor.wallet]: - Sets keys in the wallet without encryption and with overwriting enabled. """ keypair = Keypair.create_from_uri(uri) - wallet_path = "/tmp/btcli-e2e-wallet-{}".format(uri.strip("/")) + wallet_path = f"/tmp/btcli-e2e-wallet-{uri.strip('/')}" wallet = bittensor.wallet(path=wallet_path) wallet.set_coldkey(keypair=keypair, encrypt=False, overwrite=True) wallet.set_coldkeypub(keypair=keypair, encrypt=False, overwrite=True) diff --git a/tests/unit_tests/test_dendrite.py b/tests/unit_tests/test_dendrite.py index f6b101ac6..4b4609921 100644 --- a/tests/unit_tests/test_dendrite.py +++ b/tests/unit_tests/test_dendrite.py @@ -87,12 +87,12 @@ def test_init(setup_dendrite): def test_str(dendrite_obj): - expected_string = "dendrite({})".format(dendrite_obj.keypair.ss58_address) + expected_string = f"dendrite({dendrite_obj.keypair.ss58_address})" assert str(dendrite_obj) == expected_string def test_repr(dendrite_obj): - expected_string = "dendrite({})".format(dendrite_obj.keypair.ss58_address) + expected_string = f"dendrite({dendrite_obj.keypair.ss58_address})" assert repr(dendrite_obj) == expected_string