Skip to content

Commit

Permalink
[FIX] *: SyntaxWarning: invalid escape sequence
Browse files Browse the repository at this point in the history
Since python3.12 invalid escape sequences are deprecated and this will
be removed in future versions. This commit fixes all the missing escape
automatically using `ruff check --select W605 --fix`. Some will be
escaped, other may be replaced by r string.

Another solution would be to hide the deprecation warning but this would
maybe need to adapt some of the versions later leading to another
forwardport hell, lets fix it one for all once we are at it. Note that
ruff check will forbid to introduce new ones in any cases.

closes #163493

Related: odoo/enterprise#61571
Signed-off-by: Christophe Monniez (moc) <[email protected]>
  • Loading branch information
Xavier-Do committed Apr 29, 2024
1 parent 8907744 commit d6785a1
Show file tree
Hide file tree
Showing 45 changed files with 64 additions and 64 deletions.
2 changes: 1 addition & 1 deletion addons/account/models/account_account_tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def _get_tax_tags(self, tag_name, country_id):
""" Returns all the tax tags corresponding to the tag name given in parameter
in the specified country.
"""
escaped_tag_name = tag_name.replace('\\', '\\\\').replace('%', '\%').replace('_', '\_')
escaped_tag_name = tag_name.replace('\\', '\\\\').replace('%', r'\%').replace('_', r'\_')
domain = [('name', '=like', '_' + escaped_tag_name), ('country_id', '=', country_id), ('applicability', '=', 'taxes')]
return self.env['account.account.tag'].with_context(active_test=False).search(domain)

Expand Down
2 changes: 1 addition & 1 deletion addons/account/models/account_bank_statement.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ def _prepare_liquidity_move_line_vals(self):

@api.model
def _prepare_counterpart_move_line_vals(self, counterpart_vals, move_line=None):
''' Prepare values to create a new account.move.line move_line.
r''' Prepare values to create a new account.move.line move_line.
By default, without specified 'counterpart_vals' or 'move_line', the counterpart line is
created using the suspense account. Otherwise, this method is also called during the
reconciliation to prepare the statement line's journal entry. In that case,
Expand Down
4 changes: 2 additions & 2 deletions addons/account/models/account_journal.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def _default_invoice_reference_model(self):
"This is a regex that can include all the following capture groups: prefix1, year, prefix2, month, prefix3, seq, suffix.\n"\
"The prefix* groups are the separators between the year, month and the actual increasing sequence number (seq).\n"\

"e.g: ^(?P<prefix1>.*?)(?P<year>\d{4})(?P<prefix2>\D*?)(?P<month>\d{2})(?P<prefix3>\D+?)(?P<seq>\d+)(?P<suffix>\D*?)$")
r"e.g: ^(?P<prefix1>.*?)(?P<year>\d{4})(?P<prefix2>\D*?)(?P<month>\d{2})(?P<prefix3>\D+?)(?P<seq>\d+)(?P<suffix>\D*?)$")

inbound_payment_method_line_ids = fields.One2many(
comodel_name='account.payment.method.line',
Expand Down Expand Up @@ -806,7 +806,7 @@ def _create_secure_sequence(self, sequence_fields):
# -------------------------------------------------------------------------

def _get_journal_bank_account_balance(self, domain=None):
''' Get the bank balance of the current journal by filtering the journal items using the journal's accounts.
r''' Get the bank balance of the current journal by filtering the journal items using the journal's accounts.
/!\ The current journal is not part of the applied domain. This is the expected behavior since we only want
a logic based on accounts.
Expand Down
10 changes: 5 additions & 5 deletions addons/account/models/account_move.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ def _onchange_invoice_cash_rounding_id(self):

@api.model
def _get_tax_grouping_key_from_tax_line(self, tax_line):
''' Create the dictionary based on a tax line that will be used as key to group taxes together.
r''' Create the dictionary based on a tax line that will be used as key to group taxes together.
/!\ Must be consistent with '_get_tax_grouping_key_from_base_line'.
:param tax_line: An account.move.line being a tax line (with 'tax_repartition_line_id' set then).
:return: A dictionary containing all fields on which the tax will be grouped.
Expand All @@ -653,7 +653,7 @@ def _get_tax_grouping_key_from_tax_line(self, tax_line):

@api.model
def _get_tax_grouping_key_from_base_line(self, base_line, tax_vals):
''' Create the dictionary based on a base line that will be used as key to group taxes together.
r''' Create the dictionary based on a base line that will be used as key to group taxes together.
/!\ Must be consistent with '_get_tax_grouping_key_from_tax_line'.
:param base_line: An account.move.line being a base line (that could contains something in 'tax_ids').
:param tax_vals: An element of compute_all(...)['taxes'].
Expand Down Expand Up @@ -2644,7 +2644,7 @@ def _get_invoice_reference_euro_partner(self):
"""
self.ensure_one()
partner_ref = self.partner_id.ref
partner_ref_nr = re.sub('\D', '', partner_ref or '')[-21:] or str(self.partner_id.id)[-21:]
partner_ref_nr = re.sub(r'\D', '', partner_ref or '')[-21:] or str(self.partner_id.id)[-21:]
partner_ref_nr = partner_ref_nr[-21:]
check_digits = calc_check_digits('{}RF'.format(partner_ref_nr))
reference = 'RF{} {}'.format(check_digits, " ".join(["".join(x) for x in zip_longest(*[iter(partner_ref_nr)]*4, fillvalue="")]))
Expand Down Expand Up @@ -4382,7 +4382,7 @@ def _onchange_uom_id(self):

@api.onchange('account_id')
def _onchange_account_id(self):
''' Recompute 'tax_ids' based on 'account_id'.
r''' Recompute 'tax_ids' based on 'account_id'.
/!\ Don't remove existing taxes if there is no explicit taxes set on the account.
'''
for line in self:
Expand Down Expand Up @@ -5091,7 +5091,7 @@ def _mail_track(self, tracked_fields, initial):
# -------------------------------------------------------------------------

def _prepare_reconciliation_partials(self):
''' Prepare the partials on the current journal items to perform the reconciliation.
r''' Prepare the partials on the current journal items to perform the reconciliation.
/!\ The order of records in self is important because the journal items will be reconciled using this order.
:return: A recordset of account.partial.reconcile.
Expand Down
2 changes: 1 addition & 1 deletion addons/account/models/account_payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class AccountPayment(models.Model):
_check_company_auto = True

def _get_default_journal(self):
''' Retrieve the default journal for the account.payment.
r''' Retrieve the default journal for the account.payment.
/!\ This method will not override the method in 'account.move' because the ORM
doesn't allow overriding methods using _inherits. Then, this method will be called
manually in 'create' and 'new'.
Expand Down
6 changes: 3 additions & 3 deletions addons/account/models/account_reconcile_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class AccountReconcileModelLine(models.Model):
amount_string = fields.Char(string="Amount", default='100', required=True, help="""Value for the amount of the writeoff line
* Percentage: Percentage of the balance, between 0 and 100.
* Fixed: The fixed value of the writeoff. The amount will count as a debit if it is negative, as a credit if it is positive.
* From Label: There is no need for regex delimiter, only the regex is needed. For instance if you want to extract the amount from\nR:9672938 10/07 AX 9415126318 T:5L:NA BRT: 3358,07 C:\nYou could enter\nBRT: ([\d,]+)""")
* From Label: There is no need for regex delimiter, only the regex is needed. For instance if you want to extract the amount from\nR:9672938 10/07 AX 9415126318 T:5L:NA BRT: 3358,07 C:\nYou could enter\nBRT: ([\\d,]+)""")
tax_ids = fields.Many2many('account.tax', string='Taxes', ondelete='restrict', check_company=True)
analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', ondelete='set null', check_company=True)
analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags', check_company=True,
Expand All @@ -91,7 +91,7 @@ def _onchange_amount_type(self):
if self.amount_type in ('percentage', 'percentage_st_line'):
self.amount_string = '100'
elif self.amount_type == 'regex':
self.amount_string = '([\d,]+)'
self.amount_string = r'([\d,]+)'

@api.depends('amount_string')
def _compute_float_amount(self):
Expand Down Expand Up @@ -671,7 +671,7 @@ def _get_invoice_matching_query(self, st_lines_with_partner, excluded_ids):
no_partner_query = " OR ".join([
r"""
(
substring(REGEXP_REPLACE(""" + sql_field + """, '[^0-9\s]', '', 'g'), '\S(?:.*\S)*') != ''
substring(REGEXP_REPLACE(""" + sql_field + r""", '[^0-9\s]', '', 'g'), '\S(?:.*\S)*') != ''
AND
(
(""" + self._get_select_communication_flag() + """)
Expand Down
2 changes: 1 addition & 1 deletion addons/account/models/sequence_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def _deduce_sequence_number_reset(self, name):
return ret_val
raise ValidationError(_(
'The sequence regex should at least contain the seq grouping keys. For instance:\n'
'^(?P<prefix1>.*?)(?P<seq>\d*)(?P<suffix>\D*?)$'
r'^(?P<prefix1>.*?)(?P<seq>\d*)(?P<suffix>\D*?)$'
))

def _get_last_sequence_domain(self, relaxed=False):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def test_supplier_invoice_mailed_from_supplier(self):

following_partners = invoice.message_follower_ids.mapped('partner_id')
self.assertEqual(following_partners, self.env.user.partner_id)
self.assertRegex(invoice.name, 'BILL/\d{4}/\d{2}/0001')
self.assertRegex(invoice.name, r'BILL/\d{4}/\d{2}/0001')

def test_supplier_invoice_forwarded_by_internal_user_without_supplier(self):
""" In this test, the bill was forwarded by an employee,
Expand Down
2 changes: 1 addition & 1 deletion addons/base_iban/models/res_partner_bank.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


def normalize_iban(iban):
return re.sub('[\W_]', '', iban or '')
return re.sub(r'[\W_]', '', iban or '')

def pretty_iban(iban):
""" return iban in groups of four characters separated by a single space """
Expand Down
2 changes: 1 addition & 1 deletion addons/base_setup/tests/test_res_config_doc_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def setUp(self):
Set-up the test environment
"""
super(TestResConfigDocLinks, self).setUp()
self.re = re.compile("<a href=\"(\S+/documentation/\S+)\"")
self.re = re.compile("<a href=\"(\\S+/documentation/\\S+)\"")
self.links = set()

def test_01_links(self):
Expand Down
4 changes: 2 additions & 2 deletions addons/hr_expense/models/hr_expense.py
Original file line number Diff line number Diff line change
Expand Up @@ -783,13 +783,13 @@ def _parse_product(self, expense_description):
@api.model
def _parse_price(self, expense_description, currencies):
""" Return price, currency and updated description """
symbols, symbols_pattern, float_pattern = [], '', '[+-]?(\d+[.,]?\d*)'
symbols, symbols_pattern, float_pattern = [], '', r'[+-]?(\d+[.,]?\d*)'
price = 0.0
for currency in currencies:
symbols.append(re.escape(currency.symbol))
symbols.append(re.escape(currency.name))
symbols_pattern = '|'.join(symbols)
price_pattern = "((%s)?\s?%s\s?(%s)?)" % (symbols_pattern, float_pattern, symbols_pattern)
price_pattern = r"((%s)?\s?%s\s?(%s)?)" % (symbols_pattern, float_pattern, symbols_pattern)
matches = re.findall(price_pattern, expense_description)
currency = currencies and currencies[0]
if matches:
Expand Down
2 changes: 1 addition & 1 deletion addons/hw_drivers/iot_handlers/drivers/PrinterDriver.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def get_device_model(cls, device):
break
elif device.get('device-make-and-model'):
device_model = device['device-make-and-model']
return re.sub("[\(].*?[\)]", "", device_model).strip()
return re.sub(r"[\(].*?[\)]", "", device_model).strip()

@classmethod
def get_status(cls):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
parity=serial.PARITY_NONE,
timeout=0.2,
writeTimeout=0.2,
measureRegexp=b"\s*([0-9.]+)kg", # LABEL format 3 + KG in the scale settings, but Label 1/2 should work
measureRegexp=rb"\s*([0-9.]+)kg", # LABEL format 3 + KG in the scale settings, but Label 1/2 should work
statusRegexp=None,
commandTerminator=b"\r\n",
commandDelay=0.2,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get_devices_tvservice(self):
display_devices = {}
displays = subprocess.check_output(['tvservice', '-l']).decode()
x_screen = 0
for match in finditer('Display Number (\d), type HDMI (\d)', displays):
for match in finditer(r'Display Number (\d), type HDMI (\d)', displays):
display_id, hdmi_id = match.groups()
tvservice_output = subprocess.check_output(['tvservice', '-nv', display_id]).decode().strip()
if tvservice_output:
Expand Down
6 changes: 3 additions & 3 deletions addons/hw_escpos/escpos/escpos.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def text(self,text):
if text:
text = utfstr(text)
text = text.strip()
text = re.sub('\s+',' ',text)
text = re.sub(r'\s+',' ',text)
if text:
self.dirty = True
self.escpos.text(text)
Expand Down Expand Up @@ -287,7 +287,7 @@ def text(self,text):
if text:
text = utfstr(text)
text = text.strip()
text = re.sub('\s+',' ',text)
text = re.sub(r'\s+',' ',text)
if text:
self._txt(text)

Expand Down Expand Up @@ -538,7 +538,7 @@ def strclean(string):
if not string:
string = ''
string = string.strip()
string = re.sub('\s+',' ',string)
string = re.sub(r'\s+',' ',string)
return string

def format_value(value, decimals=3, width=0, decimals_separator='.', thousands_separator=',', autoint=False, symbol='', position='after'):
Expand Down
2 changes: 1 addition & 1 deletion addons/l10n_be/models/account_move.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def _get_invoice_reference_be_partner(self):
be used.
"""
self.ensure_one()
bbacomm = (re.sub('\D', '', self.partner_id.ref or '') or str(self.partner_id.id))[-10:].rjust(10, '0')
bbacomm = (re.sub(r'\D', '', self.partner_id.ref or '') or str(self.partner_id.id))[-10:].rjust(10, '0')
base = int(bbacomm)
mod = base % 97 or 97
reference = '+++%s/%s/%s%02d+++' % (bbacomm[:3], bbacomm[3:7], bbacomm[7:], mod)
Expand Down
4 changes: 2 additions & 2 deletions addons/l10n_ch/models/account_invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _compute_l10n_ch_isr_number(self):

@api.model
def _compute_isr_number(self, invoice_ref):
"""Generates the ISR or QRR reference
r"""Generates the ISR or QRR reference
An ISR references are 27 characters long.
QRR is a recycling of ISR for QR-bills. Thus works the same.
Expand Down Expand Up @@ -177,7 +177,7 @@ def _get_l10n_ch_isr_optical_amount(self):
'partner_bank_id.l10n_ch_isr_subscription_eur',
'partner_bank_id.l10n_ch_isr_subscription_chf')
def _compute_l10n_ch_isr_optical_line(self):
""" Compute the optical line to print on the bottom of the ISR.
r""" Compute the optical line to print on the bottom of the ISR.
This line is read by an OCR.
It's format is:
Expand Down
4 changes: 2 additions & 2 deletions addons/l10n_ch/models/res_bank.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _is_l10n_ch_postal(account_ref):
ref_subparts = account_ref.split('-')
account_ref = ref_subparts[0] + ref_subparts[1].rjust(6, '0') + ref_subparts[2]

if re.match('\d+$', account_ref or ''):
if re.match(r'\d+$', account_ref or ''):
account_ref_without_check = account_ref[:-1]
return mod10r(account_ref_without_check) == account_ref
return False
Expand Down Expand Up @@ -332,7 +332,7 @@ def _is_qr_reference(self, reference):
"""
return reference \
and len(reference) == 27 \
and re.match('\d+$', reference) \
and re.match(r'\d+$', reference) \
and reference == mod10r(reference[:-1])

@api.model
Expand Down
2 changes: 1 addition & 1 deletion addons/l10n_cn/__manifest__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
'author': 'www.openerp-china.org',
'maintainer': '[email protected]',
'website': 'http://openerp-china.org',
'description': """
'description': r"""
Includes the following data for the Chinese localization
========================================================
Expand Down
2 changes: 1 addition & 1 deletion addons/mail/wizard/mail_compose_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ def _get_optout_emails(self, mail_values_dict):
return []

def _onchange_template_id(self, template_id, composition_mode, model, res_id):
""" - mass_mailing: we cannot render, so return the template values
r""" - mass_mailing: we cannot render, so return the template values
- normal mode: return rendered values
/!\ for x2many field, this onchange return command instead of ids
"""
Expand Down
2 changes: 1 addition & 1 deletion addons/portal/controllers/portal.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ def _show_report(self, model, report_type, report_ref, download=False):
('Content-Length', len(report)),
]
if report_type == 'pdf' and download:
filename = "%s.pdf" % (re.sub('\W+', '-', model._get_report_base_filename()))
filename = "%s.pdf" % (re.sub(r'\W+', '-', model._get_report_base_filename()))
reporthttpheaders.append(('Content-Disposition', content_disposition(filename)))
return request.make_response(report, headers=reporthttpheaders)

Expand Down
2 changes: 1 addition & 1 deletion addons/product/models/product.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_ui
domain = expression.AND([args, domain])
product_ids = list(self._search(domain, limit=limit, access_rights_uid=name_get_uid))
if not product_ids and operator in positive_operators:
ptrn = re.compile('(\[(.*?)\])')
ptrn = re.compile(r'(\[(.*?)\])')
res = ptrn.search(name)
if res:
product_ids = list(self._search([('default_code', '=', res.group(2))] + args, limit=limit, access_rights_uid=name_get_uid))
Expand Down
2 changes: 1 addition & 1 deletion addons/purchase/models/account_invoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _get_invoice_reference(self):

@api.onchange('purchase_vendor_bill_id', 'purchase_id')
def _onchange_purchase_auto_complete(self):
''' Load from either an old purchase order, either an old vendor bill.
r''' Load from either an old purchase order, either an old vendor bill.
When setting a 'purchase.bill.union' in 'purchase_vendor_bill_id':
* If it's a vendor bill, 'invoice_vendor_bill_id' is set and the loading is done by '_onchange_invoice_vendor_bill'.
Expand Down
2 changes: 1 addition & 1 deletion addons/snailmail/models/snailmail_letter.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def _count_pages_pdf(self, bin_pdf):
:param bin_pdf : binary content of the pdf file
"""
pages = 0
for match in re.compile(b"/Count\s+(\d+)").finditer(bin_pdf):
for match in re.compile(rb"/Count\s+(\d+)").finditer(bin_pdf):
pages = int(match.group(1))
return pages

Expand Down
4 changes: 2 additions & 2 deletions addons/test_mail/data/test_mail_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@
dGVzdAo=
--089e01536c4ed4d17204e49b8e96--"""

MAIL_MULTIPART_MIXED_TWO = """X-Original-To: [email protected]
MAIL_MULTIPART_MIXED_TWO = r"""X-Original-To: [email protected]
Delivered-To: [email protected]
Received: by mail1.grosbedon.com (Postfix, from userid 10002)
id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)
Expand Down Expand Up @@ -401,7 +401,7 @@
"""


MAIL_SINGLE_BINARY = """X-Original-To: [email protected]
MAIL_SINGLE_BINARY = r"""X-Original-To: [email protected]
Delivered-To: [email protected]
Received: by mail1.grosbedon.com (Postfix, from userid 10002)
id E8166BFACA; Fri, 23 Aug 2013 13:18:01 +0200 (CEST)
Expand Down
2 changes: 1 addition & 1 deletion addons/web/controllers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ def xml2json_from_elementtree(el, preserve_whitespaces=False):
return res

class HomeStaticTemplateHelpers(object):
"""
r"""
Helper Class that wraps the reading of static qweb templates files
and xpath inheritance applied to those templates
/!\ Template inheritance order is defined by ir.module.module natural order
Expand Down
4 changes: 2 additions & 2 deletions addons/web_editor/controllers/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ def get_image_info(self, src=''):
id_match = re.search('^/web/image/([^/?]+)', src)
if id_match:
url_segment = id_match.group(1)
number_match = re.match('^(\d+)', url_segment)
number_match = re.match(r'^(\d+)', url_segment)
if '.' in url_segment: # xml-id
attachment = request.env['ir.http']._xmlid_to_obj(request.env, url_segment)
elif number_match: # numeric id
Expand Down Expand Up @@ -381,7 +381,7 @@ def _load_resources(self, file_type, views, bundles_restriction, only_user_custo

# Compile regex outside of the loop
# This will used to exclude library scss files from the result
excluded_url_matcher = re.compile("^(.+/lib/.+)|(.+import_bootstrap.+\.scss)$")
excluded_url_matcher = re.compile(r"^(.+/lib/.+)|(.+import_bootstrap.+\.scss)$")

# First check the t-call-assets used in the related views
url_infos = dict()
Expand Down
2 changes: 1 addition & 1 deletion addons/web_editor/models/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from odoo.tools import misc
from odoo.addons.base.models.assetsbundle import EXTENSIONS

_match_asset_file_url_regex = re.compile("^/(\w+)/(.+?)(\.custom\.(.+))?\.(\w+)$")
_match_asset_file_url_regex = re.compile(r"^/(\w+)/(.+?)(\.custom\.(.+))?\.(\w+)$")


class Assets(models.AbstractModel):
Expand Down
2 changes: 1 addition & 1 deletion addons/web_editor/models/ir_qweb.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ def _collapse_whitespace(text):
""" Collapses sequences of whitespace characters in ``text`` to a single
space
"""
return re.sub('\s+', ' ', text)
return re.sub(r'\s+', ' ', text)


def _realize_padding(it):
Expand Down

0 comments on commit d6785a1

Please sign in to comment.