Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sage
Path: blob/develop/src/sage_setup/util.py
4052 views
1
r"""
2
Utility functions for building Sage
3
"""
4
5
# ****************************************************************************
6
# Copyright (C) 2017 Jeroen Demeyer <[email protected]>
7
#
8
# This program is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 2 of the License, or
11
# (at your option) any later version.
12
# https://www.gnu.org/licenses/
13
# ****************************************************************************
14
15
16
def stable_uniq(L) -> list:
17
"""
18
Given an iterable L, remove duplicate items from L by keeping only
19
the last occurrence of any item.
20
21
The items must be hashable.
22
23
EXAMPLES::
24
25
sage: from sage_setup.util import stable_uniq
26
sage: stable_uniq( (1, 2, 3, 4, 5, 6, 3, 7, 5, 1, 5, 9) )
27
[2, 4, 6, 3, 7, 1, 5, 9]
28
"""
29
D = {}
30
for pos, item in enumerate(L):
31
D[item] = pos # Store the last position where an item appears
32
return sorted(D, key=lambda item: D[item])
33
34
35
def have_module(name) -> bool:
36
"""
37
Check whether a Python module named ``name`` can be imported.
38
39
This is done by trying to import that module and returning ``True``
40
if that import succeeded. So, as a side effect, the module is
41
actually imported if possible.
42
43
EXAMPLES::
44
45
sage: from sage_setup.util import have_module
46
sage: have_module("itertools")
47
True
48
sage: have_module("sage.rings.integer")
49
True
50
sage: have_module("no.such.module")
51
False
52
"""
53
try:
54
__import__(name, {}, {}, [], 0)
55
return True
56
except ImportError:
57
return False
58
59