From 8d5b9264c99caf1075aa319516e9e8e98db3938f Mon Sep 17 00:00:00 2001 From: Maciej Urbanski Date: Sat, 1 Jun 2024 15:16:52 +0200 Subject: [PATCH 1/2] replace black with ruff for formatting --- .circleci/config.yml | 52 ++++++++++++++++++++--------------------- contrib/CONTRIBUTING.md | 2 +- contrib/STYLE.md | 10 ++++---- requirements/dev.txt | 1 + 4 files changed, 34 insertions(+), 31 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 6bd5e47978..7ea959790e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -6,7 +6,7 @@ orbs: # coveralls: coveralls/coveralls@1.0.6 jobs: - black: + ruff: resource_class: small parameters: python-version: @@ -18,29 +18,29 @@ jobs: - checkout - restore_cache: - name: Restore cached black venv + name: Restore cached ruff venv keys: - - v2-pypi-py-black-<< parameters.python-version >> + - v2-pypi-py-ruff-<< parameters.python-version >> - run: - name: Update & Activate black venv + name: Update & Activate ruff venv command: | - python -m venv env/ - . env/bin/activate + python -m venv .venv + . .venv/bin/activate python -m pip install --upgrade pip - pip install black==23.7.0 + pip install ruff -c requirements/dev.txt - save_cache: - name: Save cached black venv + name: Save cached ruff venv paths: - - "env/" - key: v2-pypi-py-black-<< parameters.python-version >> + - ".venv/" + key: v2-pypi-py-ruff-<< parameters.python-version >> - run: - name: Black format check + name: Ruff format check command: | - . env/bin/activate - python -m black --exclude '(env|venv|.eggs)' --check . + . .venv/bin/activate + ruff format --diff . check_compatibility: parameters: @@ -85,8 +85,8 @@ jobs: - run: name: Update & Activate venv command: | - python -m venv env/ - . env/bin/activate + python -m venv .venv + . .venv/bin/activate python -m pip install --upgrade pip python -m pip install '.[dev]' @@ -99,20 +99,20 @@ jobs: - run: name: Install Bittensor command: | - . env/bin/activate + . .venv/bin/activate pip install -e '.[dev]' - run: name: Instantiate Mock Wallet command: | - . env/bin/activate + . .venv/bin/activate ./scripts/create_wallet.sh # TODO: Update test durations on different runs - run: name: Unit Tests command: | - . env/bin/activate + . .venv/bin/activate export PYTHONUNBUFFERED=1 pytest -n2 --reruns 3 --durations=0 --verbose --junitxml=test-results/unit_tests.xml \ --cov=. --cov-append --cov-config .coveragerc \ @@ -123,7 +123,7 @@ jobs: - run: name: Integration Tests command: | - . env/bin/activate + . .venv/bin/activate export PYTHONUNBUFFERED=1 pytest -n2 --reruns 3 --reruns-delay 15 --durations=0 --verbose --junitxml=test-results/integration_tests.xml \ --cov=. --cov-append --cov-config .coveragerc \ @@ -143,7 +143,7 @@ jobs: #- run: #name: Upload Coverage #command: | - #. env/bin/activate && coveralls + #. .venv/bin/activate && coveralls #env: #CI_NAME: circleci #CI_BUILD_NUMBER: $CIRCLE_BUILD_NUM @@ -173,8 +173,8 @@ jobs: - run: name: Update & Activate venv command: | - python -m venv env/ - . env/bin/activate + python -m venv .venv + . .venv/bin/activate python -m pip install --upgrade pip python -m pip install '.[dev]' pip install flake8 @@ -188,19 +188,19 @@ jobs: - run: name: Install Bittensor command: | - . env/bin/activate + . .venv/bin/activate pip install -e '.[dev]' - run: name: Lint with flake8 command: | - . env/bin/activate + . .venv/bin/activate python -m flake8 bittensor/ --count - run: name: Type check with mypy command: | - . env/bin/activate + . .venv/bin/activate python -m mypy --ignore-missing-imports bittensor/ unit-tests-all-python-versions: @@ -290,7 +290,7 @@ workflows: pr-requirements: jobs: - - black: + - ruff: python-version: "3.9.13" - build-and-test: matrix: diff --git a/contrib/CONTRIBUTING.md b/contrib/CONTRIBUTING.md index e1413d1099..f9f4ed5f34 100644 --- a/contrib/CONTRIBUTING.md +++ b/contrib/CONTRIBUTING.md @@ -76,7 +76,7 @@ You can contribute to Bittensor in one of two main ways (as well as many others) Here is a high-level summary: - Code consistency is crucial; adhere to established programming language conventions. -- Use `black` to format your Python code; it ensures readability and consistency. +- Use `ruff format .` to format your Python code; it ensures readability and consistency. - Write concise Git commit messages; summarize changes in ~50 characters. - Follow these six commit rules: - Atomic Commits: Focus on one task or fix per commit. diff --git a/contrib/STYLE.md b/contrib/STYLE.md index b7ac755fc0..7804359d22 100644 --- a/contrib/STYLE.md +++ b/contrib/STYLE.md @@ -58,15 +58,17 @@ Python's official style guide is PEP 8, which provides conventions for writing c #### More details -Use `black` to format your python code before commiting for consistency across such a large pool of contributors. Black's code [style](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#code-style) ensures consistent and opinionated code formatting. It automatically formats your Python code according to the Black style guide, enhancing code readability and maintainability. +Use [`ruff` to format](https://docs.astral.sh/ruff/formatter/#the-ruff-formatter) your python code before commiting for consistency across such a large pool of contributors. +Black code [style](https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html#code-style) ensures consistent and opinionated code formatting. +Ruff automatically formats your Python code according to the Black style guide, enhancing code readability and maintainability. -Key Features of Black: +Key Features of ruff & Black code style: - Consistency: Black enforces a single, consistent coding style across your project, eliminating style debates and allowing developers to focus on code logic. + Consistency: ruff enforces a single, consistent coding style across your project, eliminating style debates and allowing developers to focus on code logic. Readability: By applying a standard formatting style, Black improves code readability, making it easier to understand and collaborate on projects. - Automation: Black automates the code formatting process, saving time and effort. It eliminates the need for manual formatting and reduces the likelihood of inconsistencies. + Automation: ruff automates the code formatting process, saving time and effort. It eliminates the need for manual formatting and reduces the likelihood of inconsistencies. ### Naming Conventions diff --git a/requirements/dev.txt b/requirements/dev.txt index 2fe7007484..8fbae24589 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -13,5 +13,6 @@ types-retry==0.9.9.4 freezegun==1.5.0 torch>=1.13.1 httpx==0.27.0 +ruff==0.4.7 aioresponses==0.7.6 factory-boy==3.3.0 From 1b8068b04c6bd59d7193916ff78e945d55527479 Mon Sep 17 00:00:00 2001 From: Maciej Urbanski Date: Sat, 1 Jun 2024 15:21:19 +0200 Subject: [PATCH 2/2] apply `ruff format .` --- bittensor/axon.py | 3 +- bittensor/chain_data.py | 8 ++--- bittensor/commands/delegates.py | 32 +++++++++---------- bittensor/commands/inspect.py | 12 +++---- bittensor/commands/metagraph.py | 8 ++--- bittensor/commands/overview.py | 20 ++++++------ bittensor/commands/root.py | 2 +- bittensor/commands/senate.py | 12 +++---- bittensor/commands/stake.py | 12 +++---- bittensor/commands/weights.py | 1 - bittensor/extrinsics/commit_weights.py | 2 +- bittensor/metagraph.py | 12 ++++--- bittensor/mock/subtensor_mock.py | 22 ++++++------- bittensor/subtensor.py | 8 ++--- bittensor/utils/__init__.py | 6 ++-- bittensor/utils/networking.py | 3 +- bittensor/wallet.py | 21 ++++-------- .../weights/test_commit_weights.py | 4 ++- tests/integration_tests/test_cli.py | 4 +-- .../extrinsics/test_registration.py | 12 ++----- tests/unit_tests/extrinsics/test_root.py | 4 +-- tests/unit_tests/extrinsics/test_senate.py | 16 +++------- tests/unit_tests/extrinsics/test_staking.py | 8 ++--- tests/unit_tests/extrinsics/test_unstaking.py | 12 ++----- tests/unit_tests/test_subtensor.py | 8 +++-- tests/unit_tests/test_synapse.py | 12 +++---- tests/unit_tests/utils/test_balance.py | 4 +-- 27 files changed, 118 insertions(+), 150 deletions(-) diff --git a/bittensor/axon.py b/bittensor/axon.py index 476ed52db2..f02c45662a 100644 --- a/bittensor/axon.py +++ b/bittensor/axon.py @@ -1,5 +1,4 @@ -""" Create and initialize Axon, which services the forward and backward requests from other neurons. -""" +"""Create and initialize Axon, which services the forward and backward requests from other neurons.""" # The MIT License (MIT) # Copyright © 2021 Yuma Rao diff --git a/bittensor/chain_data.py b/bittensor/chain_data.py index 49f92e5ce6..4a9f98244c 100644 --- a/bittensor/chain_data.py +++ b/bittensor/chain_data.py @@ -833,10 +833,10 @@ def list_of_tuple_from_vec_u8( cls, vec_u8: List[int] ) -> Dict[str, List["StakeInfo"]]: """Returns a list of StakeInfo objects from a ``vec_u8``.""" - decoded: Optional[ - list[tuple[str, list[object]]] - ] = from_scale_encoding_using_type_string( - input_=vec_u8, type_string="Vec<(AccountId, Vec)>" + decoded: Optional[list[tuple[str, list[object]]]] = ( + from_scale_encoding_using_type_string( + input_=vec_u8, type_string="Vec<(AccountId, Vec)>" + ) ) if decoded is None: diff --git a/bittensor/commands/delegates.py b/bittensor/commands/delegates.py index 1fd475785c..344b2bfcea 100644 --- a/bittensor/commands/delegates.py +++ b/bittensor/commands/delegates.py @@ -83,9 +83,9 @@ def show_delegates_lite( the table in the console. """ - registered_delegate_info: Optional[ - Dict[str, DelegatesDetails] - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) if registered_delegate_info is None: bittensor.__console__.print( ":warning:[yellow]Could not get delegate info from chain.[/yellow]" @@ -206,9 +206,9 @@ def show_delegates( for prev_delegate in prev_delegates: prev_delegates_dict[prev_delegate.hotkey_ss58] = prev_delegate - registered_delegate_info: Optional[ - Dict[str, DelegatesDetails] - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) if registered_delegate_info is None: bittensor.__console__.print( ":warning:[yellow]Could not get delegate info from chain.[/yellow]" @@ -238,10 +238,10 @@ def show_delegates( "[overline white]NOMINATORS", justify="center", style="green", no_wrap=True ) table.add_column( - "[overline white]DELEGATE STAKE(\u03C4)", justify="right", no_wrap=True + "[overline white]DELEGATE STAKE(\u03c4)", justify="right", no_wrap=True ) table.add_column( - "[overline white]TOTAL STAKE(\u03C4)", + "[overline white]TOTAL STAKE(\u03c4)", justify="right", style="green", no_wrap=True, @@ -250,7 +250,7 @@ def show_delegates( table.add_column("[overline white]VPERMIT", justify="right", no_wrap=False) table.add_column("[overline white]TAKE", style="white", no_wrap=True) table.add_column( - "[overline white]NOMINATOR/(24h)/k\u03C4", style="green", justify="center" + "[overline white]NOMINATOR/(24h)/k\u03c4", style="green", justify="center" ) table.add_column("[overline white]DELEGATE/(24h)", style="green", justify="center") table.add_column("[overline white]Desc", style="rgb(50,163,219)") @@ -980,7 +980,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): style="bold green", ) table.add_column( - "[overline green]\u03C4/24h", + "[overline green]\u03c4/24h", footer_style="overline green", style="bold green", ) @@ -988,10 +988,10 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): "[overline white]NOMS", justify="center", style="green", no_wrap=True ) table.add_column( - "[overline white]OWNER STAKE(\u03C4)", justify="right", no_wrap=True + "[overline white]OWNER STAKE(\u03c4)", justify="right", no_wrap=True ) table.add_column( - "[overline white]TOTAL STAKE(\u03C4)", + "[overline white]TOTAL STAKE(\u03c4)", justify="right", style="green", no_wrap=True, @@ -1000,7 +1000,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): "[overline white]SUBNETS", justify="right", style="white", no_wrap=True ) table.add_column("[overline white]VPERMIT", justify="right", no_wrap=True) - table.add_column("[overline white]24h/k\u03C4", style="green", justify="center") + table.add_column("[overline white]24h/k\u03c4", style="green", justify="center") table.add_column("[overline white]Desc", style="rgb(50,163,219)") total_delegated = 0 @@ -1023,9 +1023,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): delegates.sort(key=lambda delegate: delegate[0].total_stake, reverse=True) total_delegated += sum(my_delegates.values()) - registered_delegate_info: Optional[ - DelegatesDetails - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[DelegatesDetails] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) if registered_delegate_info is None: bittensor.__console__.print( ":warning:[yellow]Could not get delegate info from chain.[/yellow]" diff --git a/bittensor/commands/inspect.py b/bittensor/commands/inspect.py index 76b015b774..4ef0e84c4e 100644 --- a/bittensor/commands/inspect.py +++ b/bittensor/commands/inspect.py @@ -138,9 +138,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) bittensor.logging.debug(f"Netuids to check: {netuids}") - registered_delegate_info: Optional[ - Dict[str, DelegatesDetails] - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) if registered_delegate_info is None: bittensor.__console__.print( ":warning:[yellow]Could not get delegate info from chain.[/yellow]" @@ -181,9 +181,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): "[overline white]Emission", footer_style="overline white", style="green" ) for wallet in tqdm(wallets): - delegates: List[ - Tuple[bittensor.DelegateInfo, bittensor.Balance] - ] = subtensor.get_delegated(coldkey_ss58=wallet.coldkeypub.ss58_address) + delegates: List[Tuple[bittensor.DelegateInfo, bittensor.Balance]] = ( + subtensor.get_delegated(coldkey_ss58=wallet.coldkeypub.ss58_address) + ) if not wallet.coldkeypub_file.exists_on_device(): continue cold_balance = subtensor.get_balance(wallet.coldkeypub.ss58_address) diff --git a/bittensor/commands/metagraph.py b/bittensor/commands/metagraph.py index b6999fe553..1075f50d31 100644 --- a/bittensor/commands/metagraph.py +++ b/bittensor/commands/metagraph.py @@ -159,8 +159,8 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): style="yellow", ) table.add_column( - "[overline white]STAKE(\u03C4)", - "\u03C4{:.5f}".format(total_stake), + "[overline white]STAKE(\u03c4)", + "\u03c4{:.5f}".format(total_stake), footer_style="overline white", justify="right", style="green", @@ -207,8 +207,8 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): no_wrap=True, ) table.add_column( - "[overline white]EMISSION(\u03C1)", - "\u03C1{}".format(int(total_emission)), + "[overline white]EMISSION(\u03c1)", + "\u03c1{}".format(int(total_emission)), footer_style="overline white", justify="right", style="green", diff --git a/bittensor/commands/overview.py b/bittensor/commands/overview.py index b35fd85596..b572847e49 100644 --- a/bittensor/commands/overview.py +++ b/bittensor/commands/overview.py @@ -258,9 +258,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): for neuron in neuron_list: if neuron.hotkey in checked_hotkeys: continue - total_coldkey_stake_from_metagraph[ - neuron.coldkey - ] += neuron.stake_dict[neuron.coldkey] + total_coldkey_stake_from_metagraph[neuron.coldkey] += ( + neuron.stake_dict[neuron.coldkey] + ) checked_hotkeys.add(neuron.hotkey) alerts_table = Table(show_header=True, header_style="bold magenta") @@ -483,8 +483,8 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): ) if last_subnet: table.add_column( - "[overline white]STAKE(\u03C4)", - "\u03C4{:.5f}".format(total_stake), + "[overline white]STAKE(\u03c4)", + "\u03c4{:.5f}".format(total_stake), footer_style="overline white", justify="right", style="green", @@ -493,7 +493,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): else: # No footer for non-last subnet. table.add_column( - "[overline white]STAKE(\u03C4)", + "[overline white]STAKE(\u03c4)", justify="right", style="green", no_wrap=True, @@ -539,8 +539,8 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): no_wrap=True, ) table.add_column( - "[overline white]EMISSION(\u03C1)", - "\u03C1{:_}".format(total_emission), + "[overline white]EMISSION(\u03c1)", + "\u03c1{:_}".format(total_emission), footer_style="overline white", justify="right", style="green", @@ -603,7 +603,7 @@ def overview_sort_function(row): console.clear() - caption = "[italic][dim][white]Wallet balance: [green]\u03C4" + str( + caption = "[italic][dim][white]Wallet balance: [green]\u03c4" + str( total_balance.tao ) grid.add_row(Align(caption, vertical="middle", align="center")) @@ -613,7 +613,7 @@ def overview_sort_function(row): @staticmethod def _get_neurons_for_netuid( - args_tuple: Tuple["bittensor.Config", int, List[str]] + args_tuple: Tuple["bittensor.Config", int, List[str]], ) -> Tuple[int, List["bittensor.NeuronInfoLite"], Optional[str]]: subtensor_config, netuid, hot_wallets = args_tuple diff --git a/bittensor/commands/root.py b/bittensor/commands/root.py index a3658d03ea..5607921b19 100644 --- a/bittensor/commands/root.py +++ b/bittensor/commands/root.py @@ -173,7 +173,7 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): no_wrap=True, ) table.add_column( - "[overline white]STAKE(\u03C4)", + "[overline white]STAKE(\u03c4)", footer_style="overline white", justify="right", style="green", diff --git a/bittensor/commands/senate.py b/bittensor/commands/senate.py index c92290af89..03a73cde5b 100644 --- a/bittensor/commands/senate.py +++ b/bittensor/commands/senate.py @@ -211,9 +211,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): senate_members = subtensor.get_senate_members() proposals = subtensor.get_proposals() - registered_delegate_info: Optional[ - Dict[str, DelegatesDetails] - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) table = Table(show_footer=False) table.title = ( @@ -342,9 +342,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): console.print(":cross_mark: [red]Failed[/red]: Proposal not found.") return - registered_delegate_info: Optional[ - Dict[str, DelegatesDetails] - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) table = Table(show_footer=False) table.title = "[white]Votes for Proposal {}".format(proposal_hash) diff --git a/bittensor/commands/stake.py b/bittensor/commands/stake.py index 8fe80b606a..1bc2cf2786 100644 --- a/bittensor/commands/stake.py +++ b/bittensor/commands/stake.py @@ -381,9 +381,9 @@ def _run(cli: "bittensor.cli", subtensor: "bittensor.subtensor"): wallets = _get_coldkey_wallets_for_path(cli.config.wallet.path) else: wallets = [bittensor.wallet(config=cli.config)] - registered_delegate_info: Optional[ - Dict[str, DelegatesDetails] - ] = get_delegates_details(url=bittensor.__delegates_details_url__) + registered_delegate_info: Optional[Dict[str, DelegatesDetails]] = ( + get_delegates_details(url=bittensor.__delegates_details_url__) + ) def get_stake_accounts( wallet, subtensor @@ -515,7 +515,7 @@ def get_all_wallet_accounts( ) table.add_column( "[overline white]Balance", - "\u03C4{:.5f}".format(total_balance), + "\u03c4{:.5f}".format(total_balance), footer_style="overline white", style="green", ) @@ -524,13 +524,13 @@ def get_all_wallet_accounts( ) table.add_column( "[overline white]Stake", - "\u03C4{:.5f}".format(total_stake), + "\u03c4{:.5f}".format(total_stake), footer_style="overline white", style="green", ) table.add_column( "[overline white]Rate", - "\u03C4{:.5f}/d".format(total_rate), + "\u03c4{:.5f}/d".format(total_rate), footer_style="overline white", style="green", ) diff --git a/bittensor/commands/weights.py b/bittensor/commands/weights.py index 19989c94f3..ac4d9dfc36 100644 --- a/bittensor/commands/weights.py +++ b/bittensor/commands/weights.py @@ -19,7 +19,6 @@ """Module that encapsulates the CommitWeightCommand and the RevealWeightCommand. Used to commit and reveal weights for a specific subnet on the Bittensor Network.""" - import argparse import os import re diff --git a/bittensor/extrinsics/commit_weights.py b/bittensor/extrinsics/commit_weights.py index a27e1941ba..2a526f5e96 100644 --- a/bittensor/extrinsics/commit_weights.py +++ b/bittensor/extrinsics/commit_weights.py @@ -16,7 +16,7 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -""" Module commit weights and reveal weights extrinsic. """ +"""Module commit weights and reveal weights extrinsic.""" from typing import Tuple, List diff --git a/bittensor/metagraph.py b/bittensor/metagraph.py index 8bad4d6c78..8d7e97bcc0 100644 --- a/bittensor/metagraph.py +++ b/bittensor/metagraph.py @@ -618,7 +618,9 @@ def _set_weights_and_bonds(self, subtensor: Optional[bittensor.subtensor] = None # TODO: Check and test the computation of weights and bonds if self.netuid == 0: self.weights = self._process_root_weights( - [neuron.weights for neuron in self.neurons], "weights", subtensor # type: ignore + [neuron.weights for neuron in self.neurons], + "weights", + subtensor, # type: ignore ) else: self.weights = self._process_weights_or_bonds( @@ -659,16 +661,16 @@ def _process_weights_or_bonds( if attribute == "weights": data_array.append( bittensor.utils.weight_utils.convert_weight_uids_and_vals_to_tensor( - len(self.neurons), list(uids), list(values) # type: ignore + len(self.neurons), + list(uids), + list(values), # type: ignore ) ) else: data_array.append( bittensor.utils.weight_utils.convert_bond_uids_and_vals_to_tensor( # type: ignore len(self.neurons), list(uids), list(values) - ).astype( - np.float32 - ) + ).astype(np.float32) ) tensor_param: Union["torch.nn.Parameter", NDArray] = ( ( diff --git a/bittensor/mock/subtensor_mock.py b/bittensor/mock/subtensor_mock.py index a0efe48d74..30d58f22e0 100644 --- a/bittensor/mock/subtensor_mock.py +++ b/bittensor/mock/subtensor_mock.py @@ -430,9 +430,9 @@ def _register_neuron(self, netuid: int, hotkey: str, coldkey: str) -> int: subtensor_state["Active"][netuid][uid][self.block_number] = True subtensor_state["LastUpdate"][netuid][uid] = {} - subtensor_state["LastUpdate"][netuid][uid][ + subtensor_state["LastUpdate"][netuid][uid][self.block_number] = ( self.block_number - ] = self.block_number + ) subtensor_state["Rank"][netuid][uid] = {} subtensor_state["Rank"][netuid][uid][self.block_number] = 0.0 @@ -1064,9 +1064,9 @@ def _do_nominate( else: subtensor_state["Delegates"][hotkey_ss58] = {} - subtensor_state["Delegates"][hotkey_ss58][ - self.block_number - ] = 0.18 # Constant for now + subtensor_state["Delegates"][hotkey_ss58][self.block_number] = ( + 0.18 # Constant for now + ) return True @@ -1189,9 +1189,9 @@ def _do_stake( if not wallet.coldkeypub.ss58_address in stake_state[hotkey_ss58]: stake_state[hotkey_ss58][wallet.coldkeypub.ss58_address] = {} - stake_state[hotkey_ss58][wallet.coldkeypub.ss58_address][ - self.block_number - ] = amount.rao + stake_state[hotkey_ss58][wallet.coldkeypub.ss58_address][self.block_number] = ( + amount.rao + ) # Add to total_stake storage subtensor_state["TotalStake"][self.block_number] = ( @@ -1275,9 +1275,9 @@ def _do_unstake( total_hotkey_stake_state = subtensor_state["TotalHotkeyStake"] if not hotkey_ss58 in total_hotkey_stake_state: total_hotkey_stake_state[hotkey_ss58] = {} - total_hotkey_stake_state[hotkey_ss58][ - self.block_number - ] = 0 # Shouldn't happen + total_hotkey_stake_state[hotkey_ss58][self.block_number] = ( + 0 # Shouldn't happen + ) total_coldkey_stake_state = subtensor_state["TotalColdkeyStake"] if not wallet.coldkeypub.ss58_address in total_coldkey_stake_state: diff --git a/bittensor/subtensor.py b/bittensor/subtensor.py index 46f999eb97..1b422ad276 100644 --- a/bittensor/subtensor.py +++ b/bittensor/subtensor.py @@ -20,6 +20,7 @@ The ``bittensor.subtensor`` module in Bittensor serves as a crucial interface for interacting with the Bittensor blockchain, facilitating a range of operations essential for the decentralized machine learning network. """ + import argparse import copy import functools @@ -3049,9 +3050,7 @@ def query_runtime_api( """ call_definition = bittensor.__type_registry__["runtime_api"][runtime_api][ # type: ignore "methods" # type: ignore - ][ - method - ] # type: ignore + ][method] # type: ignore json_result = self.state_call( method=f"{runtime_api}_{method}", @@ -4749,7 +4748,8 @@ def make_substrate_call_with_retry(): if block_hash: params = params + [block_hash] return self.substrate.rpc_request( - method="neuronInfo_getNeuron", params=params # custom rpc method + method="neuronInfo_getNeuron", + params=params, # custom rpc method ) json_body = make_substrate_call_with_retry() diff --git a/bittensor/utils/__init__.py b/bittensor/utils/__init__.py index 72d053ea7a..175094da87 100644 --- a/bittensor/utils/__init__.py +++ b/bittensor/utils/__init__.py @@ -207,9 +207,9 @@ def get_explorer_url_for_network( explorer_urls: Optional[Dict[str, str]] = {} # Will be None if the network is not known. i.e. not in network_map - explorer_root_urls: Optional[ - Dict[str, str] - ] = get_explorer_root_url_by_network_from_map(network, network_map) + explorer_root_urls: Optional[Dict[str, str]] = ( + get_explorer_root_url_by_network_from_map(network, network_map) + ) if explorer_root_urls != {}: # We are on a known network. diff --git a/bittensor/utils/networking.py b/bittensor/utils/networking.py index 9f1450af81..675b4e45b4 100644 --- a/bittensor/utils/networking.py +++ b/bittensor/utils/networking.py @@ -1,5 +1,4 @@ -""" Utils for handling local network with ip and ports. -""" +"""Utils for handling local network with ip and ports.""" # The MIT License (MIT) # Copyright © 2021-2022 Yuma Rao diff --git a/bittensor/wallet.py b/bittensor/wallet.py index 6ac808b12a..be6aa08c93 100644 --- a/bittensor/wallet.py +++ b/bittensor/wallet.py @@ -1,5 +1,4 @@ -""" Implementation of the wallet class, which manages balances with staking and transfer. Also manages hotkey and coldkey. -""" +"""Implementation of the wallet class, which manages balances with staking and transfer. Also manages hotkey and coldkey.""" # The MIT License (MIT) # Copyright © 2021 Yuma Rao @@ -676,8 +675,7 @@ def regenerate_coldkey( use_password: bool = True, overwrite: bool = False, suppress: bool = False, - ) -> "wallet": - ... + ) -> "wallet": ... @overload def regenerate_coldkey( @@ -686,8 +684,7 @@ def regenerate_coldkey( use_password: bool = True, overwrite: bool = False, suppress: bool = False, - ) -> "wallet": - ... + ) -> "wallet": ... @overload def regenerate_coldkey( @@ -696,8 +693,7 @@ def regenerate_coldkey( use_password: bool = True, overwrite: bool = False, suppress: bool = False, - ) -> "wallet": - ... + ) -> "wallet": ... def regenerate_coldkey( self, @@ -786,8 +782,7 @@ def regenerate_hotkey( use_password: bool = True, overwrite: bool = False, suppress: bool = False, - ) -> "wallet": - ... + ) -> "wallet": ... @overload def regenerate_hotkey( @@ -796,8 +791,7 @@ def regenerate_hotkey( use_password: bool = True, overwrite: bool = False, suppress: bool = False, - ) -> "wallet": - ... + ) -> "wallet": ... @overload def regenerate_hotkey( @@ -806,8 +800,7 @@ def regenerate_hotkey( use_password: bool = True, overwrite: bool = False, suppress: bool = False, - ) -> "wallet": - ... + ) -> "wallet": ... def regenerate_hotkey( self, diff --git a/tests/e2e_tests/subcommands/weights/test_commit_weights.py b/tests/e2e_tests/subcommands/weights/test_commit_weights.py index d22efde267..faed9d3925 100644 --- a/tests/e2e_tests/subcommands/weights/test_commit_weights.py +++ b/tests/e2e_tests/subcommands/weights/test_commit_weights.py @@ -168,7 +168,9 @@ def test_commit_and_reveal_weights(local_chain): # Query the Weights storage map revealed_weights = subtensor.query_module( - module="SubtensorModule", name="Weights", params=[1, uid] # netuid and uid + module="SubtensorModule", + name="Weights", + params=[1, uid], # netuid and uid ) # Assert that the revealed weights are set correctly diff --git a/tests/integration_tests/test_cli.py b/tests/integration_tests/test_cli.py index c20c905549..aa019c4178 100644 --- a/tests/integration_tests/test_cli.py +++ b/tests/integration_tests/test_cli.py @@ -2519,9 +2519,7 @@ def test_set_identity_command( "bittensor.wallet", return_value=mock_wallet ), patch("bittensor.__console__", MagicMock()), patch( "rich.prompt.Prompt.ask", side_effect=["y", "y"] - ), patch( - "sys.exit" - ) as mock_exit: + ), patch("sys.exit") as mock_exit: # Act if expected_exception: with pytest.raises(expected_exception) as exc_info: diff --git a/tests/unit_tests/extrinsics/test_registration.py b/tests/unit_tests/extrinsics/test_registration.py index ccae48452d..5a4d32dff6 100644 --- a/tests/unit_tests/extrinsics/test_registration.py +++ b/tests/unit_tests/extrinsics/test_registration.py @@ -269,9 +269,7 @@ def test_burned_register_extrinsic( return_value=(recycle_success, "Mock error message"), ), patch.object( mock_subtensor, "is_hotkey_registered", return_value=is_registered - ), patch( - "rich.prompt.Confirm.ask", return_value=prompt_response - ) as mock_confirm: + ), patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm: # Act result = burned_register_extrinsic( subtensor=mock_subtensor, wallet=mock_wallet, netuid=123, prompt=True @@ -313,9 +311,7 @@ def test_register_extrinsic_without_pow( mock_subtensor, "get_neuron_for_pubkey_and_subnet", return_value=MagicMock(is_null=neuron_is_null), - ), patch( - "rich.prompt.Confirm.ask", return_value=prompt_response - ), patch( + ), patch("rich.prompt.Confirm.ask", return_value=prompt_response), patch( "torch.cuda.is_available", return_value=cuda_available ): # Act @@ -374,9 +370,7 @@ def test_register_extrinsic_with_pow( mock_subtensor, "_do_pow_register", return_value=(registration_success, "key is already registered"), - ), patch( - "torch.cuda.is_available", return_value=cuda - ): + ), patch("torch.cuda.is_available", return_value=cuda): # Act if pow_success: mock_pow_solution.is_stale.return_value = pow_stale diff --git a/tests/unit_tests/extrinsics/test_root.py b/tests/unit_tests/extrinsics/test_root.py index 2bc1be632b..d3ae2c3973 100644 --- a/tests/unit_tests/extrinsics/test_root.py +++ b/tests/unit_tests/extrinsics/test_root.py @@ -189,9 +189,7 @@ def test_set_root_weights_extrinsic( mock_subtensor, "_do_set_weights", return_value=(expected_success, "Mock error") ), patch.object( mock_subtensor, "min_allowed_weights", return_value=0 - ), patch.object( - mock_subtensor, "max_weight_limit", return_value=1 - ), patch( + ), patch.object(mock_subtensor, "max_weight_limit", return_value=1), patch( "rich.prompt.Confirm.ask", return_value=user_response ) as mock_confirm: # Act diff --git a/tests/unit_tests/extrinsics/test_senate.py b/tests/unit_tests/extrinsics/test_senate.py index 8310fc38fa..66849efc5c 100644 --- a/tests/unit_tests/extrinsics/test_senate.py +++ b/tests/unit_tests/extrinsics/test_senate.py @@ -58,9 +58,7 @@ def test_register_senate_extrinsic( "bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt ), patch("bittensor.extrinsics.senate.time.sleep"), patch.object( mock_subtensor.substrate, "compose_call" - ), patch.object( - mock_subtensor.substrate, "create_signed_extrinsic" - ), patch.object( + ), patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), patch.object( mock_subtensor.substrate, "submit_extrinsic", return_value=MagicMock( @@ -153,9 +151,7 @@ def test_vote_senate_extrinsic( "bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt ), patch("bittensor.extrinsics.senate.time.sleep"), patch.object( mock_subtensor.substrate, "compose_call" - ), patch.object( - mock_subtensor.substrate, "create_signed_extrinsic" - ), patch.object( + ), patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), patch.object( mock_subtensor.substrate, "submit_extrinsic", return_value=MagicMock( @@ -219,9 +215,7 @@ def test_leave_senate_extrinsic( "bittensor.extrinsics.senate.Confirm.ask", return_value=not prompt ), patch("bittensor.extrinsics.senate.time.sleep"), patch.object( mock_subtensor.substrate, "compose_call" - ), patch.object( - mock_subtensor.substrate, "create_signed_extrinsic" - ), patch.object( + ), patch.object(mock_subtensor.substrate, "create_signed_extrinsic"), patch.object( mock_subtensor.substrate, "submit_extrinsic", return_value=MagicMock( @@ -229,9 +223,7 @@ def test_leave_senate_extrinsic( process_events=MagicMock(), error_message="error", ), - ), patch.object( - mock_wallet, "is_senate_member", return_value=is_registered - ): + ), patch.object(mock_wallet, "is_senate_member", return_value=is_registered): # Act result = leave_senate_extrinsic( subtensor=mock_subtensor, diff --git a/tests/unit_tests/extrinsics/test_staking.py b/tests/unit_tests/extrinsics/test_staking.py index 0a77ceb2c7..288e065f78 100644 --- a/tests/unit_tests/extrinsics/test_staking.py +++ b/tests/unit_tests/extrinsics/test_staking.py @@ -133,9 +133,7 @@ def test_add_stake_extrinsic( else mock_other_owner_wallet.coldkeypub.ss58_address, ), patch.object( mock_subtensor, "is_hotkey_delegate", return_value=hotkey_delegate - ), patch.object( - mock_subtensor, "get_delegate_take", return_value=0.01 - ), patch( + ), patch.object(mock_subtensor, "get_delegate_take", return_value=0.01), patch( "rich.prompt.Confirm.ask", return_value=user_accepts ) as mock_confirm: # Act @@ -506,9 +504,7 @@ def stake_side_effect(hotkey_ss58, *args, **kwargs): mock_subtensor, "_do_stake", side_effect=stake_side_effect ) as mock_do_stake, patch.object( mock_subtensor, "tx_rate_limit", return_value=0 - ), patch( - "rich.prompt.Confirm.ask", return_value=prompt_response - ) as mock_confirm: + ), patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm: # Act if exception: with pytest.raises(exception) as exc_info: diff --git a/tests/unit_tests/extrinsics/test_unstaking.py b/tests/unit_tests/extrinsics/test_unstaking.py index d6ff094dd8..6ad0a977e7 100644 --- a/tests/unit_tests/extrinsics/test_unstaking.py +++ b/tests/unit_tests/extrinsics/test_unstaking.py @@ -83,9 +83,7 @@ def test_unstake_extrinsic( mock_subtensor, "get_stake_for_coldkey_and_hotkey", return_value=mock_current_stake, - ), patch( - "rich.prompt.Confirm.ask", return_value=user_accepts - ) as mock_confirm: + ), patch("rich.prompt.Confirm.ask", return_value=user_accepts) as mock_confirm: result = unstake_extrinsic( subtensor=mock_subtensor, wallet=mock_wallet, @@ -291,15 +289,11 @@ def unstake_side_effect(hotkey_ss58, *args, **kwargs): side_effect=mock_get_minimum_required_stake, ), patch.object( mock_subtensor, "get_balance", return_value=Balance.from_tao(wallet_balance) - ), patch.object( - mock_subtensor, "tx_rate_limit", return_value=0 - ), patch.object( + ), patch.object(mock_subtensor, "tx_rate_limit", return_value=0), patch.object( mock_subtensor, "get_stake_for_coldkey_and_hotkey", return_value=mock_current_stake, - ), patch( - "rich.prompt.Confirm.ask", return_value=prompt_response - ) as mock_confirm: + ), patch("rich.prompt.Confirm.ask", return_value=prompt_response) as mock_confirm: # Act if exception: with pytest.raises(exception) as exc_info: diff --git a/tests/unit_tests/test_subtensor.py b/tests/unit_tests/test_subtensor.py index 3709ec190d..72ee3b2d23 100644 --- a/tests/unit_tests/test_subtensor.py +++ b/tests/unit_tests/test_subtensor.py @@ -1191,9 +1191,11 @@ def test_total_stake_no_block(mocker, subtensor): # Asserts assert result is not None subtensor.query_subtensor.assert_called_once_with("TotalStake", None) - spy_balance_from_rao.assert_called_once_with( - subtensor.query_subtensor.return_value.value - ), + ( + spy_balance_from_rao.assert_called_once_with( + subtensor.query_subtensor.return_value.value + ), + ) # `serving_rate_limit` method tests diff --git a/tests/unit_tests/test_synapse.py b/tests/unit_tests/test_synapse.py index e28265dc24..b0ce4f1325 100644 --- a/tests/unit_tests/test_synapse.py +++ b/tests/unit_tests/test_synapse.py @@ -131,12 +131,12 @@ class Test(bittensor.Synapse): c: Optional[int] # Required, carried through headers, cannot be None d: Optional[list[int]] # Required, carried though headers, cannot be None e: list[int] # Carried through headers - f: Optional[ - int - ] = None # Not Required, Not carried through headers, can be None - g: Optional[ - list[int] - ] = None # Not Required, Not carried though headers, can be None + f: Optional[int] = ( + None # Not Required, Not carried through headers, can be None + ) + g: Optional[list[int]] = ( + None # Not Required, Not carried though headers, can be None + ) # Create an instance of the custom Synapse subclass synapse = Test( diff --git a/tests/unit_tests/utils/test_balance.py b/tests/unit_tests/utils/test_balance.py index 129af42f01..b99bc111f2 100644 --- a/tests/unit_tests/utils/test_balance.py +++ b/tests/unit_tests/utils/test_balance.py @@ -209,8 +209,8 @@ def test_balance_mul(balance: Union[int, float], balance2: Union[int, float]): prod_ = balance_ * balance2_ assert isinstance(prod_, Balance) - assert prod_.rao == pytest.approx( - rao_ * rao2_, 9 + assert ( + prod_.rao == pytest.approx(rao_ * rao2_, 9) ), f"{balance_} * {balance2_} == {prod_.rao} != {rao_} * {balance2} == {rao_ * balance2}"