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

DTZ rules: Clarify error messages and docs #10621

Merged
merged 7 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,14 @@ use ruff_macros::{derive_message_formats, violation};

use ruff_python_ast::{self as ast};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::rules::flake8_datetimez::rules::helpers::has_non_none_keyword;

use super::helpers;
use super::helpers::{self, DatetimeModuleAntipattern};

/// ## What it does
/// Checks for usage of `datetime.datetime.fromtimestamp()` without a `tz`
/// argument.
/// Checks for usage of `datetime.datetime.fromtimestamp()` that do not specify
/// a timezone.
///
/// ## Why is this bad?
/// Python datetime objects can be naive or timezone-aware. While an aware
Expand All @@ -21,8 +19,9 @@ use super::helpers;
/// datetime objects. Since this can lead to errors, it is recommended to
/// always use timezone-aware objects.
///
/// `datetime.datetime.fromtimestamp(ts)` returns a naive datetime object.
/// Instead, use `datetime.datetime.fromtimestamp(ts, tz=)` to return a
/// `datetime.datetime.fromtimestamp(ts)` or
/// `datetime.datetime.fromtimestampe(ts, tz=None)` returns a naive datetime
/// object. Instead, use `datetime.datetime.fromtimestamp(ts, tz=)` to return a
/// timezone-aware object.
///
/// ## Example
Expand All @@ -39,7 +38,7 @@ use super::helpers;
/// datetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc)
/// ```
///
/// Or, for Python 3.11 and later:
/// Or, on Python 3.11 and later:
/// ```python
/// import datetime
///
Expand All @@ -49,14 +48,20 @@ use super::helpers;
/// ## References
/// - [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)
#[violation]
pub struct CallDatetimeFromtimestamp;
pub struct CallDatetimeFromtimestamp(DatetimeModuleAntipattern);

impl Violation for CallDatetimeFromtimestamp {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"The use of `datetime.datetime.fromtimestamp()` without `tz` argument is not allowed"
)
let CallDatetimeFromtimestamp(antipattern) = self;
match antipattern {
DatetimeModuleAntipattern::NoTzArgumentPassed => format!(
"The use of `datetime.datetime.fromtimestamp()` without `tz` argument is not allowed"
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
),
DatetimeModuleAntipattern::NonePassedToTzArgument => format!(
"Passing `tz=None` is forbidden, as it creates a naive datetime object"
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
),
}
}
}

Expand All @@ -82,26 +87,14 @@ pub(crate) fn call_datetime_fromtimestamp(checker: &mut Checker, call: &ast::Exp
return;
}

// no args / no args unqualified
if call.arguments.args.len() < 2 && call.arguments.keywords.is_empty() {
checker
.diagnostics
.push(Diagnostic::new(CallDatetimeFromtimestamp, call.range()));
return;
}

// none args
if call.arguments.args.len() > 1 && call.arguments.args[1].is_none_literal_expr() {
checker
.diagnostics
.push(Diagnostic::new(CallDatetimeFromtimestamp, call.range()));
return;
}
let antipattern = match call.arguments.find_argument("tz", 1) {
Some(ast::Expr::NoneLiteral(_)) => DatetimeModuleAntipattern::NonePassedToTzArgument,
Some(_) => return,
None => DatetimeModuleAntipattern::NoTzArgumentPassed,
};

// wrong keywords / none keyword
if !call.arguments.keywords.is_empty() && !has_non_none_keyword(&call.arguments, "tz") {
checker
.diagnostics
.push(Diagnostic::new(CallDatetimeFromtimestamp, call.range()));
}
checker.diagnostics.push(Diagnostic::new(
CallDatetimeFromtimestamp(antipattern),
call.range,
));
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};

use ruff_python_ast::{self as ast, Expr};
use ruff_python_ast as ast;
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::rules::flake8_datetimez::rules::helpers::has_non_none_keyword;

use super::helpers;
use super::helpers::{self, DatetimeModuleAntipattern};

/// ## What it does
/// Checks for usage of `datetime.datetime.now()` without a `tz` argument.
/// Checks for usages of `datetime.datetime.now()` that do not specify a timezone.
///
/// ## Why is this bad?
/// Python datetime objects can be naive or timezone-aware. While an aware
Expand All @@ -20,8 +18,9 @@ use super::helpers;
/// datetime objects. Since this can lead to errors, it is recommended to
/// always use timezone-aware objects.
///
/// `datetime.datetime.now()` returns a naive datetime object. Instead, use
/// `datetime.datetime.now(tz=)` to return a timezone-aware object.
/// `datetime.datetime.now()` or `datetime.datetime.now(tz=None)` returns a naive
/// datetime object. Instead, use `datetime.datetime.now(tz=)` to return a
/// timezone-aware object.
///
/// ## Example
/// ```python
Expand All @@ -47,12 +46,20 @@ use super::helpers;
/// ## References
/// - [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)
#[violation]
pub struct CallDatetimeNowWithoutTzinfo;
pub struct CallDatetimeNowWithoutTzinfo(DatetimeModuleAntipattern);

impl Violation for CallDatetimeNowWithoutTzinfo {
#[derive_message_formats]
fn message(&self) -> String {
format!("The use of `datetime.datetime.now()` without `tz` argument is not allowed")
let CallDatetimeNowWithoutTzinfo(antipattern) = self;
match antipattern {
DatetimeModuleAntipattern::NoTzArgumentPassed => {
format!("Using `datetime.datetime.now()` without a `tz=` argument is not allowed")
}
DatetimeModuleAntipattern::NonePassedToTzArgument => {
format!("Passing `tz=None` to `datetime.datetime.now()` is not allowed")
}
}
}
}

Expand All @@ -75,31 +82,14 @@ pub(crate) fn call_datetime_now_without_tzinfo(checker: &mut Checker, call: &ast
return;
}

// no args / no args unqualified
if call.arguments.args.is_empty() && call.arguments.keywords.is_empty() {
checker
.diagnostics
.push(Diagnostic::new(CallDatetimeNowWithoutTzinfo, call.range()));
return;
}
let antipattern = match call.arguments.find_argument("tz", 0) {
Some(ast::Expr::NoneLiteral(_)) => DatetimeModuleAntipattern::NonePassedToTzArgument,
Some(_) => return,
None => DatetimeModuleAntipattern::NoTzArgumentPassed,
};

// none args
if call
.arguments
.args
.first()
.is_some_and(Expr::is_none_literal_expr)
{
checker
.diagnostics
.push(Diagnostic::new(CallDatetimeNowWithoutTzinfo, call.range()));
return;
}

// wrong keywords / none keyword
if !call.arguments.keywords.is_empty() && !has_non_none_keyword(&call.arguments, "tz") {
checker
.diagnostics
.push(Diagnostic::new(CallDatetimeNowWithoutTzinfo, call.range()));
}
checker.diagnostics.push(Diagnostic::new(
CallDatetimeNowWithoutTzinfo(antipattern),
call.range,
));
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Expr};
use ruff_python_semantic::Modules;
use ruff_text_size::Ranged;

use crate::checkers::ast::Checker;
use crate::rules::flake8_datetimez::rules::helpers::has_non_none_keyword;

use super::helpers::DatetimeModuleAntipattern;

/// ## What it does
/// Checks for uses of `datetime.datetime.strptime()` that lead to naive
Expand Down Expand Up @@ -51,15 +51,22 @@ use crate::rules::flake8_datetimez::rules::helpers::has_non_none_keyword;
/// - [Python documentation: Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects)
/// - [Python documentation: `strftime()` and `strptime()` Behavior](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)
#[violation]
pub struct CallDatetimeStrptimeWithoutZone;
pub struct CallDatetimeStrptimeWithoutZone(DatetimeModuleAntipattern);

impl Violation for CallDatetimeStrptimeWithoutZone {
#[derive_message_formats]
fn message(&self) -> String {
format!(
"The use of `datetime.datetime.strptime()` without %z must be followed by \
`.replace(tzinfo=)` or `.astimezone()`"
)
let CallDatetimeStrptimeWithoutZone(antipattern) = self;
match antipattern {
DatetimeModuleAntipattern::NoTzArgumentPassed => format!(
"The use of `datetime.datetime.strptime()` without %z must be followed by \
`.replace(tzinfo=)` or `.astimezone()`"
),
DatetimeModuleAntipattern::NonePassedToTzArgument => format!(
"Passing `tzinfo=None` to `datetime.datetime.replace()` is forbidden, \
as it creates a naive datetime object"
),
}
}
}

Expand Down Expand Up @@ -91,36 +98,44 @@ pub(crate) fn call_datetime_strptime_without_zone(checker: &mut Checker, call: &
}
};

let (Some(grandparent), Some(parent)) = (
checker.semantic().current_expression_grandparent(),
checker.semantic().current_expression_parent(),
) else {
let semantic = checker.semantic();
if let Some(antipattern) = find_antipattern(
semantic.current_expression_grandparent(),
semantic.current_expression_parent(),
) {
checker.diagnostics.push(Diagnostic::new(
CallDatetimeStrptimeWithoutZone,
call.range(),
CallDatetimeStrptimeWithoutZone(antipattern),
call.range,
));
return;
};

if let Expr::Call(ast::ExprCall { arguments, .. }) = grandparent {
if let Expr::Attribute(ast::ExprAttribute { attr, .. }) = parent {
let attr = attr.as_str();
// Ex) `datetime.strptime(...).astimezone()`
if attr == "astimezone" {
return;
}

// Ex) `datetime.strptime(...).replace(tzinfo=UTC)`
if attr == "replace" {
if has_non_none_keyword(arguments, "tzinfo") {
return;
}
}
}
}
}

checker.diagnostics.push(Diagnostic::new(
CallDatetimeStrptimeWithoutZone,
call.range(),
));
fn find_antipattern(
grandparent: Option<&Expr>,
parent: Option<&Expr>,
) -> Option<DatetimeModuleAntipattern> {
let Some(Expr::Call(ast::ExprCall { arguments, .. })) = grandparent else {
return Some(DatetimeModuleAntipattern::NoTzArgumentPassed);
};
let Some(Expr::Attribute(ast::ExprAttribute { attr, .. })) = parent else {
return Some(DatetimeModuleAntipattern::NoTzArgumentPassed);
};
// Ex) `datetime.strptime(...).astimezone()`
if attr == "astimezone" {
return None;
}
if attr != "replace" {
return Some(DatetimeModuleAntipattern::NoTzArgumentPassed);
}
match arguments.find_keyword("tzinfo") {
// Ex) `datetime.strptime(...).replace(tz=None)`
Some(ast::Keyword {
value: Expr::NoneLiteral(_),
..
}) => Some(DatetimeModuleAntipattern::NonePassedToTzArgument),
// Ex) `datetime.strptime(...).replace(tz=...)`
Some(_) => None,
// Ex) `datetime.strptime(...).replace(...)` with no tz= argument
None => Some(DatetimeModuleAntipattern::NoTzArgumentPassed),
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@ use super::helpers;
/// datetime objects. Since this can lead to errors, it is recommended to
/// always use timezone-aware objects.
///
/// `datetime.datetime.utcfromtimestamp()` returns a naive datetime object;
/// instead, use `datetime.datetime.fromtimestamp(ts, tz=)` to return a
/// `datetime.datetime.utcfromtimestamp()` or
/// `datetime.datetime.utcfromtimestamp(tz=None)` returns a naive datetime
/// object; instead, use `datetime.datetime.fromtimestamp(ts, tz=)` to return a
/// timezone-aware object.
///
/// ## Example
/// ```python
/// import datetime
///
/// datetime.datetime.utcfromtimestamp()
/// datetime.datetime.utcfromtimestamp(946684800)
/// ```
///
/// Use instead:
Expand All @@ -37,7 +38,7 @@ use super::helpers;
/// datetime.datetime.fromtimestamp(946684800, tz=datetime.timezone.utc)
/// ```
///
/// Or, for Python 3.11 and later:
/// Or, on Python 3.11 and later:
/// ```python
/// import datetime
///
Expand Down