Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

some pylint tidyups #502

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/comment-docs-preview-in-pr/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class PartialGithubEvent(BaseModel):
"body": f"📝 Docs preview for commit {use_pr.head.sha} at: {settings.input_deploy_url}"
},
)
if not (200 <= response.status_code <= 300):
if not 200 <= response.status_code <= 300:
Copy link
Member

@svlandeg svlandeg Mar 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When there's multiple if statements (implicit here because of the chaining) combined with a negation, I personally find keeping the parentheses more clear & readable - so I would vote to revert this change.

logging.error(f"Error posting comment: {response.text}")
sys.exit(1)
logging.info("Finished")
4 changes: 2 additions & 2 deletions docs_src/subcommands/tutorial001/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import typer

import items
import users

import typer

app = typer.Typer()
app.add_typer(users.app, name="users")
app.add_typer(items.app, name="items")
Expand Down
4 changes: 2 additions & 2 deletions docs_src/subcommands/tutorial003/lands.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import typer

import reigns
import towns

import typer

app = typer.Typer()
app.add_typer(reigns.app, name="reigns")
app.add_typer(towns.app, name="towns")
Expand Down
4 changes: 2 additions & 2 deletions docs_src/subcommands/tutorial003/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import typer

import items
import lands
import users

import typer

app = typer.Typer()
app.add_typer(users.app, name="users")
app.add_typer(items.app, name="items")
Expand Down
3 changes: 1 addition & 2 deletions docs_src/terminating/tutorial001.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ def maybe_create_user(username: str):
if username in existing_usernames:
print("The user already exists")
raise typer.Exit()
else:
print(f"User created: {username}")
print(f"User created: {username}")
Comment on lines 7 to +10
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Throughout the docs, the house style is to use else even if the preceding if raises or returns. While I agree with you that this is not strictly necessary, I do think it contributes to readability to have the else explicitly there. Furthermore, it's more robust in terms of maintenance down the line: if the original if statement ever changes its implementation, the developer won't have to worry about implicit else statements being affected. So overall I think verbosity is prefered in these cases.



def send_new_user_notification(username: str):
Expand Down
2 changes: 1 addition & 1 deletion docs_src/using_click/tutorial001.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo("Hello %s!" % name)
click.echo(f"Hello {name}!")
Comment on lines 7 to +10
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While F-strings are typically nicer and more readable, there are a few cases where you might prefer not using them. When we're logging things for instance, you might prefer avoiding the str() functionality for cases where the statement wouldn't actually get logged (e.g. if the logging level is higher). That said - I'm not actually sure how click.echo() operates under the hood so I'm not sure whether we want this rewrite in this case or not.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! This one is just that it was an exact copy of Click's tutorial. But they now updated it to use f-strings, so I would take this change. 🤓

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cf #891



if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion docs_src/using_click/tutorial003.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def callback():
@click.option("--name", prompt="Your name", help="The person to greet.")
def hello(name):
"""Simple program that greets NAME for a total of COUNT times."""
click.echo("Hello %s!" % name)
click.echo(f"Hello {name}!")


typer_click_object = typer.main.get_command(app)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_completion/test_completion_complete.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def test_completion_complete_subcommand_zsh_files():
"_TYPER_COMPLETE_TESTING": "True",
},
)
assert ("_files") in result.stdout
assert "_files" in result.stdout


def test_completion_complete_subcommand_fish():
Expand Down Expand Up @@ -177,4 +177,4 @@ def test_completion_complete_subcommand_noshell():
"_TYPER_COMPLETE_TESTING": "True",
},
)
assert ("") in result.stdout
assert "" in result.stdout
4 changes: 2 additions & 2 deletions tests/test_completion/test_completion_complete_no_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def test_completion_complete_subcommand_powershell():
"_TYPER_COMPLETE_TESTING": "True",
},
)
assert ("create::: \ndelete::: ") in result.stdout
assert "create::: \ndelete::: " in result.stdout


def test_completion_complete_subcommand_pwsh():
Expand All @@ -68,4 +68,4 @@ def test_completion_complete_subcommand_pwsh():
"_TYPER_COMPLETE_TESTING": "True",
},
)
assert ("create::: \ndelete::: ") in result.stdout
assert "create::: \ndelete::: " in result.stdout
2 changes: 1 addition & 1 deletion tests/test_completion/test_completion_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def test_completion_install_fish():

def test_completion_install_powershell():
completion_path: Path = (
Path.home() / f".config/powershell/Microsoft.PowerShell_profile.ps1"
Path.home() / ".config/powershell/Microsoft.PowerShell_profile.ps1"
)
completion_path_bytes = f"{completion_path}\n".encode("windows-1252")
text = ""
Expand Down
68 changes: 35 additions & 33 deletions typer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,38 +2,40 @@

__version__ = "0.7.0"

from shutil import get_terminal_size as get_terminal_size
from shutil import get_terminal_size

from click.exceptions import Abort as Abort
from click.exceptions import BadParameter as BadParameter
from click.exceptions import Exit as Exit
from click.termui import clear as clear
from click.termui import confirm as confirm
from click.termui import echo_via_pager as echo_via_pager
from click.termui import edit as edit
from click.termui import getchar as getchar
from click.termui import launch as launch
from click.termui import pause as pause
from click.termui import progressbar as progressbar
from click.termui import prompt as prompt
from click.termui import secho as secho
from click.termui import style as style
from click.termui import unstyle as unstyle
from click.utils import echo as echo
from click.utils import format_filename as format_filename
from click.utils import get_app_dir as get_app_dir
from click.utils import get_binary_stream as get_binary_stream
from click.utils import get_text_stream as get_text_stream
from click.utils import open_file as open_file
from click.exceptions import Abort, BadParameter, Exit
from click.termui import (
clear,
confirm,
echo_via_pager,
edit,
getchar,
launch,
pause,
progressbar,
prompt,
secho,
style,
unstyle,
)
from click.utils import (
echo,
format_filename,
get_app_dir,
get_binary_stream,
get_text_stream,
open_file,
)

from . import colors as colors
from .main import Typer as Typer
from .main import run as run
from .models import CallbackParam as CallbackParam
from .models import Context as Context
from .models import FileBinaryRead as FileBinaryRead
from .models import FileBinaryWrite as FileBinaryWrite
from .models import FileText as FileText
from .models import FileTextWrite as FileTextWrite
from .params import Argument as Argument
from .params import Option as Option
from . import colors
from .main import Typer, run
from .models import (
CallbackParam,
Context,
FileBinaryRead,
FileBinaryWrite,
FileText,
FileTextWrite,
)
from .params import Argument, Option
2 changes: 1 addition & 1 deletion typer/_compat_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


def _get_click_major() -> int:
return int(click.__version__.split(".")[0])
return int(click.__version__.split(".", maxsplit=1)[0])
8 changes: 4 additions & 4 deletions typer/_completion_click7.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,11 @@ def do_powershell_complete(cli: click.Command, prog_name: str) -> bool:
def do_shell_complete(*, cli: click.Command, prog_name: str, shell: str) -> bool:
if shell == "bash":
return do_bash_complete(cli, prog_name)
elif shell == "zsh":
if shell == "zsh":
return do_zsh_complete(cli, prog_name)
elif shell == "fish":
if shell == "fish":
return do_fish_complete(cli, prog_name)
elif shell in {"powershell", "pwsh"}:
if shell in {"powershell", "pwsh"}:
return do_powershell_complete(cli, prog_name)
return False

Expand All @@ -130,7 +130,7 @@ def handle_shell_complete(
)
)
return True
elif command == "complete":
if command == "complete":
return do_shell_complete(cli=cli, prog_name=prog_name, shell=shell)
click.echo(f'Completion instruction "{command}" not supported.', err=True)
return False
Expand Down
9 changes: 3 additions & 6 deletions typer/_completion_click8.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,7 @@ def escape(s: str) -> str:
# return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
if item.help:
return f'"{escape(item.value)}":"{escape(item.help)}"'
else:
return f'"{escape(item.value)}"'
return f'"{escape(item.value)}"'

def complete(self) -> str:
args, incomplete = self.get_completion_args()
Expand All @@ -103,8 +102,7 @@ def complete(self) -> str:
if res:
args_str = "\n".join(res)
return f"_arguments '*: :(({args_str}))'"
else:
return "_files"
return "_files"


class FishComplete(click.shell_completion.FishComplete):
Expand Down Expand Up @@ -139,8 +137,7 @@ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
if item.help:
formatted_help = re.sub(r"\s", " ", item.help)
return f"{item.value}\t{formatted_help}"
else:
return f"{item.value}"
return f"{item.value}"

def complete(self) -> str:
complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")
Expand Down
16 changes: 6 additions & 10 deletions typer/_completion_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@
shellingham = None


from typing import Optional


class Shells(str, Enum):
bash = "bash"
zsh = "zsh"
Expand Down Expand Up @@ -92,7 +89,7 @@ def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> s
return (
script
% dict(
complete_func="_{}_completion".format(cf_name),
complete_func=f"_{cf_name}_completion",
prog_name=prog_name,
autocomplete_var=complete_var,
)
Expand Down Expand Up @@ -224,21 +221,20 @@ def install(
prog_name=prog_name, complete_var=complete_var, shell=shell
)
return shell, installed_path
elif shell == "zsh":
if shell == "zsh":
installed_path = install_zsh(
prog_name=prog_name, complete_var=complete_var, shell=shell
)
return shell, installed_path
elif shell == "fish":
if shell == "fish":
installed_path = install_fish(
prog_name=prog_name, complete_var=complete_var, shell=shell
)
return shell, installed_path
elif shell in {"powershell", "pwsh"}:
if shell in {"powershell", "pwsh"}:
installed_path = install_powershell(
prog_name=prog_name, complete_var=complete_var, shell=shell
)
return shell, installed_path
else:
click.echo(f"Shell {shell} is not supported.")
raise click.exceptions.Exit(1)
click.echo(f"Shell {shell} is not supported.")
raise click.exceptions.Exit(1)
2 changes: 1 addition & 1 deletion typer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def make_metavar(self) -> str:
return self.metavar
var = (self.name or "").upper()
if not self.required:
var = "[{}]".format(var)
var = f"[{var}]"
type_var = self.type.get_metavar(self)
if type_var:
var += f":{type_var}"
Expand Down
Loading