Skip to content

Commit 02a7894

Browse files
authored
Fix #571 deprecation warnings Python 3.12 (#585)
- Change default test.max_case_secs to 300, because a Sirepo test takes longer than 2min.
1 parent 1e98292 commit 02a7894

17 files changed

Lines changed: 103 additions & 73 deletions

File tree

pykern/package_data/projex/projex/__init__.py.jinja

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
{{ copyright_license_rst }}
44
"""
5-
import pkg_resources
5+
import importlib.metadata
66

77
try:
88
# We only have a version once the package is installed.
9-
__version__ = pkg_resources.get_distribution("{{ name }}").version
10-
except pkg_resources.DistributionNotFound:
9+
__version__ = importlib.metadata.version("{{ name }}")
10+
except importlib.metadata.PackageNotFoundError:
1111
pass

pykern/pkcli/github.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import pykern.pkcollections
1919
import os
2020
import os.path
21+
import pykern.pkcompat
2122
import re
2223
import subprocess
2324
import sys
@@ -268,7 +269,7 @@ def issue_update_alpha_pending(repo):
268269
g.login()
269270
for c in r.commits(
270271
sha="master",
271-
since=datetime.datetime.now() - datetime.timedelta(minutes=24 * 60),
272+
since=pykern.pkcompat.utcnow() - datetime.timedelta(minutes=24 * 60),
272273
):
273274
m = re.search(r"([-\w]+/[-\w]+)?#(\d+)", c.message)
274275
if not m:
@@ -421,7 +422,7 @@ def _repos():
421422
return _try(lambda: self.list_org_repos(org, include_forks=True))
422423

423424
# POSIT: timestamps are sorted in _clone()
424-
self._date_d = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
425+
self._date_d = pykern.pkcompat.utcnow().strftime("%Y%m%d%H%M%S")
425426
with pkio.save_chdir(self._date_d, mkdir=True):
426427
for r in _repos():
427428
pkdlog("{}: begin", r.full_name)
@@ -438,9 +439,9 @@ def _prev_backup(self, base, ext):
438439
return b[-1] if b else []
439440

440441
def _purge(self):
441-
expires = datetime.datetime.utcnow() - cfg.keep_days
442+
expires = pykern.pkcompat.utcnow() - cfg.keep_days
442443
for d in pkio.sorted_glob("[0-9]" * len(self._date_d)):
443-
t = datetime.datetime.utcfromtimestamp(d.stat().mtime)
444+
t = datetime.datetime.fromtimestamp(d.stat().mtime, datetime.timezone.utc)
444445
if t < expires:
445446
pkio.unchecked_remove(d)
446447

@@ -488,7 +489,7 @@ def _issue(i, d):
488489
k = PKDict(state="all")
489490
if prev:
490491
self._extract_backup(prev)
491-
k.since = datetime.datetime.now() - datetime.timedelta(days=7)
492+
k.since = pykern.pkcompat.utcnow() - datetime.timedelta(days=7)
492493
for i in _try(lambda: list(repo.issues(**k))):
493494
_try(lambda: _issue(i, d))
494495
_tar(base)
@@ -627,7 +628,7 @@ def _release_title(channel, pending=False):
627628
x = (
628629
"[pending]"
629630
if pending
630-
else datetime.datetime.utcnow()
631+
else pykern.pkcompat.utcnow()
631632
.replace(
632633
microsecond=0,
633634
)

pykern/pkcli/projex.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@
1111
from pykern.pkcollections import PKDict
1212
from pykern.pkdebug import pkdc, pkdp
1313
import copy
14-
import datetime
1514
import os
1615
import py.path
16+
import pykern.pkcompat
1717
import re
1818
import subprocess
1919

2020
#: Default values
2121
DEFAULTS = {
22-
"year": datetime.datetime.now().year,
22+
"year": pykern.pkcompat.utcnow().year,
2323
"license": "apache2",
2424
"copyright_license_rst": """:copyright: Copyright (c) {year} {author}. All Rights Reserved.
2525
:license: {license}""",

pykern/pkcli/rsmanifest.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""Create and read global and user manifests.
32
43
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
@@ -33,9 +32,7 @@ def add_code(name, version, uri, source_d, virtual_env=None, pyenv=None):
3332
virtual_env (str): DEPRECATED
3433
pyenv (str): pyenv version
3534
"""
36-
from pykern import pkcollections
37-
from pykern import pkio
38-
from pykern import pkjson
35+
from pykern import pkcollections, pkio, pkjson, pkcompat
3936
import datetime
4037
import json
4138

@@ -58,7 +55,7 @@ def add_code(name, version, uri, source_d, virtual_env=None, pyenv=None):
5855
pyenv = _NO_PYENV
5956
v = values.codes.get(pyenv) or pkcollections.Dict()
6057
v[name.lower()] = pkcollections.Dict(
61-
installed=datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
58+
installed=pkcompat.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
6259
name=name,
6360
source_d=source_d,
6461
uri=uri,

pykern/pkcli/sim.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
# -*- coding: utf-8 -*-
21
"""wrapper for running simulations
32
43
:copyright: Copyright (c) 2017 RadiaSoft LLC. All Rights Reserved.
54
:license: http://www.apache.org/licenses/LICENSE-2.0.html
65
"""
7-
from __future__ import absolute_import, division, print_function
6+
87
from pykern import pkconfig
8+
import pykern.pkcompat
99

1010
#: Where we install files with pip
1111
_PYTHON_USER_BASE = "rsbase"
@@ -164,12 +164,11 @@ def _init_git():
164164
"""Init git locally and to bitbucket"""
165165
from pykern import pkcli
166166
from pykern import pkio
167-
import datetime
168167
import re
169168
import subprocess
170169

171170
title = pkio.py_path().basename
172-
v = datetime.datetime.utcnow().strftime("%Y%m%d-%H%M%S")
171+
v = pykern.pkcompat.utcnow().strftime("%Y%m%d-%H%M%S")
173172
name = "sim-{}-{}".format(pkio.py_path().basename, v).lower()
174173
r, ctx = _git_api_request(
175174
"post",
@@ -240,14 +239,13 @@ def _rsmanifest():
240239
from pykern import pkjson
241240
from pykern.pkcli import rsmanifest
242241
import cpuinfo
243-
import datetime
244242
import os
245243
import subprocess
246244

247245
m = rsmanifest.read_all()
248246
m["sim"] = {
249247
"run": {
250-
"datetime": datetime.datetime.utcnow().isoformat(),
248+
"datetime": pykern.pkcompat.utcnow().isoformat(),
251249
"cpu_info": cpuinfo.get_cpu_info(),
252250
"pyenv": _pyenv_version(),
253251
# TODO(robnagler) can't include because of auth/credential

pykern/pkcli/test.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@
1010
from pykern import pkunit
1111
from pykern.pkcollections import PKDict
1212
from pykern.pkdebug import pkdp
13-
import datetime
1413
import os
1514
import pykern.pkcli
15+
import pykern.pkcompat
1616
import re
1717
import signal
1818
import subprocess
@@ -22,7 +22,7 @@
2222

2323
SUITE_D = "tests"
2424
_COROUTINE_NEVER_AWAITED = re.compile(
25-
"(.+ coroutine \S+ was never awaited.*)", flags=re.MULTILINE
25+
r"(.+ coroutine \S+ was never awaited.*)", flags=re.MULTILINE
2626
)
2727
_TEST_SKIPPED = re.compile(r"^.+\s+SKIPPED\s+\(.+\)$", flags=re.MULTILINE)
2828
_TEST_PY = re.compile(r"_test\.py$")
@@ -45,7 +45,7 @@
4545

4646
_cfg = pkconfig.init(
4747
ignore_warnings=(False, bool, "override pytest's output of all warnings"),
48-
max_case_secs=(120, pkconfig.parse_seconds, "max run time for a case"),
48+
max_case_secs=(300, pkconfig.parse_seconds, "max run time for a case"),
4949
max_failures=(
5050
5,
5151
pkconfig.parse_positive_int,
@@ -120,7 +120,7 @@ def run(self):
120120
self.tries -= 1
121121
self.restartable = self.tries > 0
122122
self.process = self._start()
123-
self.started = datetime.datetime.utcnow()
123+
self.started = pykern.pkcompat.utcnow()
124124

125125
def _exit(self, returncode, aborting):
126126
def _forced_fail(msg):
@@ -376,7 +376,7 @@ def _check_run_time(case, now):
376376
case.kill_after_timeout(t)
377377

378378
while self.cases:
379-
n = datetime.datetime.utcnow()
379+
n = pykern.pkcompat.utcnow()
380380
for c in self.cases:
381381
if (m := c.is_done(aborting)) is None:
382382
# wait for next loop

pykern/pkcompat.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""Backwards and forward compatible Python utilities
32
43
Functions here will be available forever, even when functions are
@@ -10,9 +9,10 @@
109
1110
:copyright: Copyright (c) 2015-2023 RadiaSoft LLC. All Rights Reserved.
1211
:license: http://www.apache.org/licenses/LICENSE-2.0.html
13-
1412
"""
13+
1514
# Limit pykern imports so avoid dependency issues for pkconfig
15+
import datetime
1616
import inspect
1717
import itertools
1818
import locale
@@ -96,6 +96,17 @@ def unicode_unescape(value):
9696
return value.encode("utf-8").decode("unicode-escape")
9797

9898

99+
def utcnow():
100+
"""Replace deprecated datetime.utcnow
101+
102+
datetime.UTC does not exist in 3.9 so easier to wrap here.
103+
104+
Returns:
105+
datetime.datetime: current time in UTC
106+
"""
107+
return datetime.datetime.now(datetime.timezone.utc)
108+
109+
99110
def zip_strict(*iterables):
100111
"""`zip` where iterables must be exact.
101112

pykern/pkdebug.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""Logging or regex-controlled print statements
32
43
We take the view that there are two types of logging: permanent
@@ -80,6 +79,7 @@ def my_function():
8079
:license: http://www.apache.org/licenses/LICENSE-2.0.html
8180
8281
"""
82+
8383
from pykern import pkcompat
8484
from pykern import pkconfig
8585
from pykern import pkconst
@@ -351,7 +351,7 @@ def emit(self, record):
351351
),
352352
lambda: (
353353
record.process,
354-
datetime.datetime.utcfromtimestamp(record.created),
354+
datetime.datetime.fromtimestamp(record.created, datetime.timezone.utc),
355355
),
356356
with_control=wc,
357357
)
@@ -565,7 +565,7 @@ def msg():
565565
return pkdformat(fmt, *args, **kwargs)
566566

567567
def pid_time():
568-
return (os.getpid(), datetime.datetime.utcnow())
568+
return (os.getpid(), pkcompat.utcnow())
569569

570570
def prefix():
571571
return pkinspect.Call(

pykern/pkresource.py

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,29 @@
1111
import errno
1212
import glob
1313
import importlib
14-
import pkg_resources
1514
import os.path
15+
import sys
16+
17+
from pykern.pkdebug import pkdp
18+
19+
if sys.version_info < (3, 10):
20+
# There's a bug resources.files() in 3.9.15 so need this.
21+
# Also works with older versions than 3.9
22+
import pkg_resources
23+
24+
def _resource_filename(package, path):
25+
return pkg_resources.resource_filename(
26+
package,
27+
os.path.join(pkconst.PACKAGE_DATA, path),
28+
)
29+
30+
else:
31+
import importlib.resources
32+
33+
def _resource_filename(package, path):
34+
return str(
35+
importlib.resources.files(package).joinpath(pkconst.PACKAGE_DATA, path)
36+
)
1637

1738

1839
def file_path(relative_filename, caller_context=None, packages=None):
@@ -62,14 +83,13 @@ def glob_paths(relative_path, caller_context=None, packages=None):
6283
py.path: absolute paths of the matched files
6384
"""
6485
r = []
65-
a = []
6686
for f, p in _files(relative_path, caller_context, packages):
67-
a.append(p)
6887
r.extend(glob.glob(f))
6988
return [pkio.py_path(f) for f in r]
7089

7190

7291
def _files(path, caller_context, packages):
92+
7393
if caller_context and packages:
7494
raise ValueError(
7595
f"Use only one of caller_context={caller_context} and packages={packages}",
@@ -86,11 +106,7 @@ def _files(path, caller_context, packages):
86106
)
87107
):
88108
yield (
89-
# Will be fixed in https://github.com/radiasoft/pykern/issues/462
90-
pkg_resources.resource_filename(
91-
p,
92-
os.path.join(pkconst.PACKAGE_DATA, path),
93-
),
109+
_resource_filename(p, path),
94110
p,
95111
)
96112

pykern/pksetup.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,9 @@ def _version(base):
415415
global _cfg
416416

417417
if not _cfg:
418-
_cfg = pkconfig.init(no_version=(False, bool, "use utcnow as version"))
418+
_cfg = pkconfig.init(
419+
no_version=(False, bool, "use now(datetime.timezone.utc)s version")
420+
)
419421
if _cfg.no_version:
420422
return _version_from_datetime(), None
421423
v1 = _version_from_pkg_info(base)
@@ -439,7 +441,9 @@ def _version_from_datetime(value=None):
439441
# Avoid 'UserWarning: Normalizing' by setuptools
440442
return str(
441443
packaging.version.Version(
442-
(value or datetime.datetime.utcnow()).strftime("%Y%m%d.%H%M%S"),
444+
(value or datetime.datetime.now(datetime.timezone.utc)).strftime(
445+
"%Y%m%d.%H%M%S"
446+
),
443447
),
444448
)
445449

0 commit comments

Comments
 (0)