jenkins-bot has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1155608?usp=email )

Change subject: IMPR: Use stacklevel=2 with warnings.warn
......................................................................

IMPR: Use stacklevel=2 with warnings.warn

Change-Id: I4d0f45ca402887f4e058853c059151732c2ee009
---
M pywikibot/bot.py
M pywikibot/comms/http.py
M pywikibot/config.py
M pywikibot/data/api/_requests.py
M pywikibot/login.py
M pywikibot/page/_basepage.py
M pywikibot/page/_toolforge.py
M pywikibot/scripts/wrapper.py
M pywikibot/site/_apisite.py
M pywikibot/site/_basesite.py
M pywikibot/tools/__init__.py
M pywikibot/version.py
12 files changed, 27 insertions(+), 25 deletions(-)

Approvals:
  jenkins-bot: Verified
  Xqt: Looks good to me, approved




diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index adb70e1..9a2be57 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -739,7 +739,7 @@
     """
     if pywikibot._sites:
         warnings.warn('Site objects have been created before arguments were '
-                      'handled', UserWarning)
+                      'handled', UserWarning, stacklevel=2)

     # get commandline arguments if necessary
     if not args:
@@ -1161,7 +1161,7 @@
         if 'generator' in kwargs:
             if hasattr(self, 'generator'):
                 warnings.warn(f'{type(self).__name__} has a generator'
-                              ' already. Ignoring argument.')
+                              ' already. Ignoring argument.', stacklevel=2)
             else:
                 self.generator: Iterable = kwargs.pop('generator')

diff --git a/pywikibot/comms/http.py b/pywikibot/comms/http.py
index e5d9b37..3d2f26a 100644
--- a/pywikibot/comms/http.py
+++ b/pywikibot/comms/http.py
@@ -300,7 +300,7 @@

             warn(f'config.authenticate[{path!r}] has invalid value.\n'
                  f'It should contain 2 or 4 items, not {length}.\n'
-                 f'See {pywikibot.__url__}/OAuth for more info.')
+                 f'See {pywikibot.__url__}/OAuth for more info.', stacklevel=2)

     return None

diff --git a/pywikibot/config.py b/pywikibot/config.py
index 55e1916..e56469a 100644
--- a/pywikibot/config.py
+++ b/pywikibot/config.py
@@ -1012,19 +1012,19 @@
                     value = _assert_default_type(name, value,
                                                  default_values[name])
             except _DifferentTypeError as e:
-                warn(e)
+                warn(e, stacklevel=2)
             else:
                 user_config[name] = value
         elif not name.startswith('_') and name not in skipped:
             if name in _deprecated_variables:
                 warn('\n' + fill(DEPRECATED_VARIABLE.format(name)),
-                     _ConfigurationDeprecationWarning)
+                     _ConfigurationDeprecationWarning, stacklevel=2)
             else:
                 warn('\n' + fill(f'Configuration variable "{name}" is defined '
                                  f'in your {user_config_file} but unknown. It'
                                  ' can be a misspelled one or a variable that'
                                  ' is no longer supported.'),
-                     UserWarning)
+                     UserWarning, stacklevel=2)


 _check_user_config_types(_exec_globals, _public_globals, _imports)
@@ -1039,7 +1039,7 @@
     if _right_user_agent_format != _exec_globals['user_agent_format']:
         warn('`{httplib2}` in user_agent_format is deprecated, '
              'will replace `{httplib2}` with `{http_backend}`',
-             _ConfigurationDeprecationWarning)
+             _ConfigurationDeprecationWarning, stacklevel=2)
         _exec_globals['user_agent_format'] = _right_user_agent_format
     del _right_user_agent_format

@@ -1048,7 +1048,7 @@

     if _key in _deprecated_variables:
         warn(DEPRECATED_VARIABLE.format(_key),
-             _ConfigurationDeprecationWarning)
+             _ConfigurationDeprecationWarning, stacklevel=2)

 # If we cannot auto-detect the console encoding (e.g. when piping data)
 # assume utf-8. On Linux, this will typically be correct; on Windows,
diff --git a/pywikibot/data/api/_requests.py b/pywikibot/data/api/_requests.py
index 33f9fd5..b68f132 100644
--- a/pywikibot/data/api/_requests.py
+++ b/pywikibot/data/api/_requests.py
@@ -265,7 +265,7 @@
         # TODO: Use ParamInfo request to determine valid parameters
         if isinstance(kwargs.get('parameters'), dict):
             warn('The request contains already a "parameters" entry which is '
-                 'a dict.')
+                 'a dict.', stacklevel=2)
         return cls(site=req_site, parameters=kwargs)

     @classmethod
diff --git a/pywikibot/login.py b/pywikibot/login.py
index a3679c7..c6fb669 100644
--- a/pywikibot/login.py
+++ b/pywikibot/login.py
@@ -139,7 +139,7 @@
             warn('When using BotPasswords it is recommended that you store'
                  ' your login credentials in a password_file instead. See '
                  f'{__url__}/BotPasswords for instructions and more'
-                 ' information.')
+                 ' information.', stacklevel=2)
             main_username = self.username.partition('@')[0]

         try:
@@ -260,13 +260,13 @@

             if not isinstance(entry, tuple):
                 warn(f'Invalid tuple in line {line_len - n}',
-                     _PasswordFileWarning)
+                     _PasswordFileWarning, stacklevel=2)
                 continue

             if not 2 <= (entry_len := len(entry)) <= 4:
                 warn(f'The length of tuple in line {line_len - n} should be 2 '
                      f'to 4, {entry_len} given ({entry})',
-                     _PasswordFileWarning)
+                     _PasswordFileWarning, stacklevel=2)
                 continue

             code, family, username, password = (
@@ -284,7 +284,8 @@
                     self.login_name = password.login_name(self.username)
                     break

-                warn('Invalid password format', _PasswordFileWarning)
+                warn('Invalid password format', _PasswordFileWarning,
+                     stacklevel=2)

     _api_error = {
         'NotExists': 'does not exist',
@@ -554,7 +555,7 @@
         """
         if '@' in suffix:
             warn('The BotPassword entry should only include the suffix',
-                 _PasswordFileWarning)
+                 _PasswordFileWarning, stacklevel=2)
         self.suffix = suffix
         self.password = password

@@ -597,7 +598,7 @@
                 f'Password exists in password file for {self.site}: '
                 f'{self.username}. Password is unnecessary and should be'
                 ' removed if OAuth enabled.',
-                _PasswordFileWarning
+                _PasswordFileWarning, stacklevel=2
             )
         self._consumer_token = (user, password)
         self._access_token: tuple[str, str] | None = None
diff --git a/pywikibot/page/_basepage.py b/pywikibot/page/_basepage.py
index 20301e3..9cbd4eb 100644
--- a/pywikibot/page/_basepage.py
+++ b/pywikibot/page/_basepage.py
@@ -2186,7 +2186,7 @@
             undelete_revs = []
         if reason is None:
             warn('Not passing a reason for undelete() is deprecated.',
-                 DeprecationWarning)
+                 DeprecationWarning, stacklevel=2)
             pywikibot.info(f'Undeleting {self.title(as_link=True)}.')
             reason = pywikibot.input(
                 'Please enter a reason for the undeletion:')
diff --git a/pywikibot/page/_toolforge.py b/pywikibot/page/_toolforge.py
index a5d6d54..e491b88 100644
--- a/pywikibot/page/_toolforge.py
+++ b/pywikibot/page/_toolforge.py
@@ -172,7 +172,7 @@
         :raise TimeoutError: WikiHistory timeout
         """
         if n and n > 5:
-            warn('Only the first 5 authors can be given.')
+            warn('Only the first 5 authors can be given.', stacklevel=2)

         baseurl = 'https://wikihistory.toolforge.org'
         pattern = (r'><bdi>(?P<author>.+?)</bdi></a>\s'
diff --git a/pywikibot/scripts/wrapper.py b/pywikibot/scripts/wrapper.py
index 9396ad2..62cbac8 100755
--- a/pywikibot/scripts/wrapper.py
+++ b/pywikibot/scripts/wrapper.py
@@ -411,7 +411,7 @@
         else:
             warn("'user_script_paths' must be a list,\n"
                  f'found: {type(config.user_script_paths).__name__}.'
-                 ' Ignoring this setting.')
+                 ' Ignoring this setting.', stacklevel=2)

     found = test_paths(user_script_paths, Path(config.base_dir))
     if found:  # pragma: no cover
@@ -519,7 +519,7 @@
                 module = import_module(file_package)
             except ImportError as e:
                 warn(f'Parent module {file_package} not found: {e}',
-                     ImportWarning)
+                     ImportWarning, stacklevel=2)

     help_option = any(arg.startswith('-help:') or arg == '-help'
                       for arg in script_args)
diff --git a/pywikibot/site/_apisite.py b/pywikibot/site/_apisite.py
index 9480955..eb103c5 100644
--- a/pywikibot/site/_apisite.py
+++ b/pywikibot/site/_apisite.py
@@ -2102,7 +2102,7 @@
                     f"{self.user()} is within 'bot' group but 'bot' right"
                     " wasn't activated with OAuth or BotPassword settings"
                 )
-                warn(msg)
+                warn(msg, stacklevel=2)

         params = dict(
             action='edit',
diff --git a/pywikibot/site/_basesite.py b/pywikibot/site/_basesite.py
index 28a33a4..9973973 100644
--- a/pywikibot/site/_basesite.py
+++ b/pywikibot/site/_basesite.py
@@ -83,7 +83,7 @@
                     pywikibot.config.mylang = self.__code
                     warn('Global configuration variable "mylang" changed to '
                          f'"{self.__code}" while instantiating site {self}',
-                         UserWarning)
+                         UserWarning, stacklevel=2)
             else:
                 error_msg = (f"Language '{self.__code}' does not exist in "
                              f'family {self.__family.name}')
diff --git a/pywikibot/tools/__init__.py b/pywikibot/tools/__init__.py
index 8fcae2d..d9aa74e 100644
--- a/pywikibot/tools/__init__.py
+++ b/pywikibot/tools/__init__.py
@@ -138,7 +138,7 @@

         if module_version < required_version:
             warn(f'Module version {module_version} is lower than requested '
-                 f'version {required_version}', ImportWarning)
+                 f'version {required_version}', ImportWarning, stacklevel=2)
             return False

     return True
@@ -687,7 +687,8 @@
         os.chmod(filename, mode)
         # re-read and check changes
         if os.stat(filename).st_mode != st_mode and not quiet:
-            warn(warn_str.format(filename, st_mode - stat.S_IFREG, mode))
+            warn(warn_str.format(filename, st_mode - stat.S_IFREG, mode),
+                 stacklevel=2)


 def compute_file_hash(filename: str | os.PathLike,
diff --git a/pywikibot/version.py b/pywikibot/version.py
index 9af081e..a5e00df 100644
--- a/pywikibot/version.py
+++ b/pywikibot/version.py
@@ -105,7 +105,7 @@
         tag, rev, date, hsh = (
             '', '-1 (unknown)', '0 (unknown)', '(unknown)')
         warn(f'Unable to detect version; exceptions raised:\n{exceptions!r}',
-             UserWarning)
+             UserWarning, stacklevel=2)
         exceptions = None

     # Git and SVN can silently fail, as it may be a nightly.
@@ -117,7 +117,7 @@
     elif isinstance(date, time.struct_time):
         datestring = time.strftime('%Y/%m/%d, %H:%M:%S', date)
     else:  # pragma: no cover
-        warn('Unable to detect package date', UserWarning)
+        warn('Unable to detect package date', UserWarning, stacklevel=2)
         datestring = '-2 (unknown)'

     return {'tag': tag, 'rev': rev, 'date': datestring, 'hsh': hsh}

--
To view, visit 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1155608?usp=email
To unsubscribe, or for help writing mail filters, visit 
https://gerrit.wikimedia.org/r/settings?usp=email

Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I4d0f45ca402887f4e058853c059151732c2ee009
Gerrit-Change-Number: 1155608
Gerrit-PatchSet: 2
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to