Skip to content

Commit

Permalink
Use boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Dec 11, 2023
1 parent b19e86e commit ce3d2b2
Show file tree
Hide file tree
Showing 7 changed files with 28 additions and 95 deletions.
8 changes: 5 additions & 3 deletions crates/ruff_linter/src/rules/flake8_type_checking/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::rules::flake8_type_checking::settings::Settings;
use anyhow::Result;
use rustc_hash::FxHashSet;

use ruff_diagnostics::Edit;
use ruff_python_ast::call_path::from_qualified_name;
use ruff_python_ast::helpers::{map_callable, map_subscript};
Expand All @@ -8,7 +9,8 @@ use ruff_python_codegen::Stylist;
use ruff_python_semantic::{Binding, BindingId, BindingKind, NodeId, SemanticModel};
use ruff_source_file::Locator;
use ruff_text_size::Ranged;
use rustc_hash::FxHashSet;

use crate::rules::flake8_type_checking::settings::Settings;

pub(crate) fn is_valid_runtime_import(
binding: &Binding,
Expand All @@ -30,7 +32,7 @@ pub(crate) fn is_valid_runtime_import(
|| reference.in_typing_only_annotation()
|| reference.in_complex_string_type_definition()
|| reference.in_simple_string_type_definition()
|| (settings.annotation_strategy.is_quote()
|| (settings.quote_annotations
&& reference.in_runtime_evaluated_annotation()))
})
} else {
Expand Down
3 changes: 1 addition & 2 deletions crates/ruff_linter/src/rules/flake8_type_checking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ mod tests {
use test_case::test_case;

use crate::registry::{Linter, Rule};
use crate::rules::flake8_type_checking::settings::AnnotationStrategy;
use crate::test::{test_path, test_snippet};
use crate::{assert_messages, settings};

Expand Down Expand Up @@ -63,7 +62,7 @@ mod tests {
Path::new("flake8_type_checking").join(path).as_path(),
&settings::LinterSettings {
flake8_type_checking: super::settings::Settings {
annotation_strategy: AnnotationStrategy::Quote,
quote_annotations: true,
..Default::default()
},
..settings::LinterSettings::for_rule(rule_code)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,18 +145,13 @@ pub(crate) fn runtime_import_in_type_checking_block(
} else {
// Determine whether the member should be fixed by moving the import out of the
// type-checking block, or by quoting its references.
if checker
.settings
.flake8_type_checking
.annotation_strategy
.is_quote()
if checker.settings.flake8_type_checking.quote_annotations
&& binding.references().all(|reference_id| {
let reference = checker.semantic().reference(reference_id);
reference.context().is_typing()
|| reference.in_runtime_evaluated_annotation()
})
{
println!("quote");
quotes_by_statement.entry(node_id).or_default().push(import);
} else {
moves_by_statement.entry(node_id).or_default().push(import);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,11 +281,7 @@ pub(crate) fn typing_only_runtime_import(
|| reference.in_typing_only_annotation()
|| reference.in_complex_string_type_definition()
|| reference.in_simple_string_type_definition()
|| (checker
.settings
.flake8_type_checking
.annotation_strategy
.is_quote()
|| (checker.settings.flake8_type_checking.quote_annotations
&& reference.in_runtime_evaluated_annotation())
})
{
Expand Down
24 changes: 2 additions & 22 deletions crates/ruff_linter/src/rules/flake8_type_checking/settings.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
//! Settings for the `flake8-type-checking` plugin.
use ruff_macros::CacheKey;
use serde::{Deserialize, Serialize};

#[derive(Debug, CacheKey)]
pub struct Settings {
pub strict: bool,
pub exempt_modules: Vec<String>,
pub runtime_evaluated_base_classes: Vec<String>,
pub runtime_evaluated_decorators: Vec<String>,
pub annotation_strategy: AnnotationStrategy,
pub quote_annotations: bool,
}

impl Default for Settings {
Expand All @@ -19,26 +18,7 @@ impl Default for Settings {
exempt_modules: vec!["typing".to_string(), "typing_extensions".to_string()],
runtime_evaluated_base_classes: vec![],
runtime_evaluated_decorators: vec![],
annotation_strategy: AnnotationStrategy::Preserve,
quote_annotations: false,
}
}
}

#[derive(
Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, CacheKey, is_macro::Is,
)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum AnnotationStrategy {
/// Avoid changing the semantics of runtime-evaluated annotations (e.g., by quoting them, or
/// inserting `from __future__ import annotations`). Imports will be classified as typing-only
/// or runtime-required based exclusively on the existing type annotations.
#[default]
Preserve,
/// Quote runtime-evaluated annotations, if doing so would enable the corresponding import to
/// be moved into an `if TYPE_CHECKING:` block.
Quote,
/// Insert `from __future__ import annotations` at the top of the file, if doing so would enable
/// an import to be moved into an `if TYPE_CHECKING:` block.
Future,
}
32 changes: 11 additions & 21 deletions crates/ruff_workspace/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use ruff_linter::rules::flake8_pytest_style::settings::SettingsError;
use ruff_linter::rules::flake8_pytest_style::types;
use ruff_linter::rules::flake8_quotes::settings::Quote;
use ruff_linter::rules::flake8_tidy_imports::settings::{ApiBan, Strictness};
use ruff_linter::rules::flake8_type_checking::settings::AnnotationStrategy;
use ruff_linter::rules::isort::settings::RelativeImportsOrder;
use ruff_linter::rules::isort::{ImportSection, ImportType};
use ruff_linter::rules::pydocstyle::settings::Convention;
Expand Down Expand Up @@ -1642,8 +1641,8 @@ pub struct Flake8TypeCheckingOptions {
)]
pub runtime_evaluated_decorators: Option<Vec<String>>,

/// The strategy to use when analyzing type annotations that, by default,
/// Python would evaluate at runtime.
/// Whether to add quotes around type annotations, if doing so would allow
/// the corresponding import to be moved into a type-checking block.
///
/// For example, in the following, Python requires that `Sequence` be
/// available at runtime, despite the fact that it's only used in a type
Expand All @@ -1658,31 +1657,22 @@ pub struct Flake8TypeCheckingOptions {
/// In other words, moving `from collections.abc import Sequence` into an
/// `if TYPE_CHECKING:` block above would cause a runtime error.
///
/// By default, Ruff will respect such runtime evaluations (`"preserve"`),
/// but supports two alternative strategies for handling them:
///
/// - `"quote"`: Add quotes around the annotation (e.g., `"Sequence[int]"`), to
/// prevent Python from evaluating it at runtime. Adding quotes around
/// `Sequence` above will allow Ruff to move the import into an
/// `if TYPE_CHECKING:` block.
/// - `"future"`: Add a `from __future__ import annotations` import at the
/// top of the file, which will cause Python to treat all annotations as
/// strings, rather than evaluating them at runtime.
///
/// Setting `annotation-strategy` to `"quote"` or `"future"` will allow
/// Ruff to move more imports into type-checking blocks, but may cause
/// issues with other tools that expect annotations to be evaluated at
/// runtime.
/// By default, Ruff will respect such runtime evaluations. However,
/// setting `annotation-strategy` to `"quote"` will instruct Ruff to
/// add quotes around the annotation (e.g., `"Sequence[int]"`), to
/// prevent Python from evaluating it at runtime. Adding quotes around
/// `Sequence` above will allow Ruff to move the import into an
/// `if TYPE_CHECKING:` block.
#[option(
default = "[]",
value_type = r#""preserve" | "quote" | "future""#,
example = r#"
# Add quotes around type annotations, if doing so would allow
# an import to be moved into a type-checking block.
annotation-strategy = "quote"
quote-annotations = true
"#
)]
pub annotation_strategy: Option<AnnotationStrategy>,
pub quote_annotations: Option<bool>,
}

impl Flake8TypeCheckingOptions {
Expand All @@ -1694,7 +1684,7 @@ impl Flake8TypeCheckingOptions {
.unwrap_or_else(|| vec!["typing".to_string()]),
runtime_evaluated_base_classes: self.runtime_evaluated_base_classes.unwrap_or_default(),
runtime_evaluated_decorators: self.runtime_evaluated_decorators.unwrap_or_default(),
annotation_strategy: self.annotation_strategy.unwrap_or_default(),
quote_annotations: self.quote_annotations.unwrap_or_default(),
}
}
}
Expand Down
43 changes: 7 additions & 36 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit ce3d2b2

Please sign in to comment.