Skip to content

Commit a56cc26

Browse files
authored
Support generating a random seed from the command-line arguments. (#160)
* Rewrite utils.py; Add function comments. * Support generating a random seed from the command-line arguments * Add the functions __all__ * Fix some warnings * Use another way to process args; write tests
1 parent b4faa53 commit a56cc26

File tree

5 files changed

+104
-41
lines changed

5 files changed

+104
-41
lines changed

cyaron/tests/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55
from .compare_test import TestCompare
66
from .graph_test import TestGraph
77
from .vector_test import TestVector
8+
from .general_test import TestGeneral

cyaron/tests/compare_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515
class TestCompare(unittest.TestCase):
1616

1717
def setUp(self):
18+
self.original_directory = os.getcwd()
1819
self.temp_directory = tempfile.mkdtemp()
1920
os.chdir(self.temp_directory)
2021

2122
def tearDown(self):
23+
os.chdir(self.original_directory)
2224
try:
2325
shutil.rmtree(self.temp_directory)
2426
except:

cyaron/tests/general_test.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import subprocess
2+
import unittest
3+
import os
4+
import tempfile
5+
import shutil
6+
import sys
7+
8+
9+
class TestGeneral(unittest.TestCase):
10+
11+
def setUp(self):
12+
self.original_directory = os.getcwd()
13+
self.temp_directory = tempfile.mkdtemp()
14+
os.chdir(self.temp_directory)
15+
16+
def tearDown(self):
17+
os.chdir(self.original_directory)
18+
try:
19+
shutil.rmtree(self.temp_directory)
20+
except:
21+
pass
22+
23+
def test_randseed_arg(self):
24+
with open("test_randseed.py", 'w', encoding='utf-8') as f:
25+
f.write("import cyaron as c\n"
26+
"c.process_args()\n"
27+
"for i in range(10):\n"
28+
" print(c.randint(1,1000000000),end=' ')\n")
29+
30+
env = os.environ.copy()
31+
env['PYTHONPATH'] = self.original_directory + os.pathsep + env.get(
32+
'PYTHONPATH', '')
33+
result = subprocess.run([
34+
sys.executable, 'test_randseed.py',
35+
'--randseed=pinkrabbit147154220'
36+
],
37+
env=env,
38+
stdout=subprocess.PIPE,
39+
universal_newlines=True,
40+
check=True)
41+
self.assertEqual(
42+
result.stdout,
43+
"243842479 490459912 810766286 646030451 191412261 929378523 273000814 982402032 436668773 957169453 "
44+
)

cyaron/tests/io_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@
1212
class TestIO(unittest.TestCase):
1313

1414
def setUp(self):
15+
self.original_directory = os.getcwd()
1516
self.temp_directory = tempfile.mkdtemp()
1617
os.chdir(self.temp_directory)
1718

1819
def tearDown(self):
20+
os.chdir(self.original_directory)
1921
try:
2022
shutil.rmtree(self.temp_directory)
2123
except:

cyaron/utils.py

Lines changed: 55 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,67 +1,81 @@
1-
def ati(array):
2-
"""ati(array) -> list
3-
Convert all the elements in the array and return them in a list.
4-
"""
1+
"""Some utility functions."""
2+
import sys
3+
import random
4+
from typing import cast, Any, Dict, Iterable, Tuple, Union
5+
6+
__all__ = [
7+
"ati", "list_like", "int_like", "strtolines", "make_unicode",
8+
"unpack_kwargs", "process_args"
9+
]
10+
11+
12+
def ati(array: Iterable[Any]):
13+
"""Convert all the elements in the array and return them in a list."""
514
return [int(i) for i in array]
615

716

8-
def list_like(data):
9-
"""list_like(data) -> bool
10-
Judge whether the object data is like a list or a tuple.
11-
object data -> the data to judge
12-
"""
17+
def list_like(data: Any):
18+
"""Judge whether the object data is like a list or a tuple."""
1319
return isinstance(data, (tuple, list))
1420

1521

16-
def int_like(data):
17-
isint = False
18-
try:
19-
isint = isint or isinstance(data, long)
20-
except NameError:
21-
pass
22-
isint = isint or isinstance(data, int)
23-
return isint
22+
def int_like(data: Any):
23+
"""Judge whether the object data is like a int."""
24+
return isinstance(data, int)
2425

2526

26-
def strtolines(str):
27-
lines = str.split('\n')
28-
for i in range(len(lines)):
27+
def strtolines(string: str):
28+
"""
29+
Split the string by the newline character, remove trailing spaces from each line,
30+
and remove any blank lines at the end of the the string.
31+
"""
32+
lines = string.split("\n")
33+
for i, _ in enumerate(lines):
2934
lines[i] = lines[i].rstrip()
3035

31-
while len(lines) > 0 and len(lines[len(lines) - 1]) == 0:
32-
del lines[len(lines) - 1]
36+
while len(lines) > 0 and len(lines[-1]) == 0:
37+
lines.pop()
3338
return lines
3439

3540

36-
def make_unicode(data):
41+
def make_unicode(data: Any):
42+
"""Convert the data to a string."""
3743
return str(data)
3844

3945

40-
def unpack_kwargs(funcname, kwargs, arg_pattern):
46+
def unpack_kwargs(
47+
funcname: str,
48+
kwargs: Dict[str, Any],
49+
arg_pattern: Iterable[Union[str, Tuple[str, Any]]],
50+
):
51+
"""Parse the keyword arguments."""
4152
rv = {}
4253
kwargs = kwargs.copy()
4354
for tp in arg_pattern:
4455
if list_like(tp):
45-
k, v = tp
46-
rv[k] = kwargs.get(k, v)
47-
try:
48-
del kwargs[k]
49-
except KeyError:
50-
pass
56+
k, v = cast(Tuple[str, Any], tp)
57+
rv[k] = kwargs.pop(k, v)
5158
else:
52-
error = False
59+
tp = cast(str, tp)
5360
try:
54-
rv[tp] = kwargs[tp]
55-
del kwargs[tp]
56-
except KeyError as e:
57-
error = True
58-
if error:
61+
rv[tp] = kwargs.pop(tp)
62+
except KeyError:
5963
raise TypeError(
60-
'{}() missing 1 required keyword-only argument: \'{}\''.
61-
format(funcname, tp))
64+
f"{funcname}() missing 1 required keyword-only argument: '{tp}'"
65+
) from None
6266
if kwargs:
6367
raise TypeError(
64-
'{}() got an unexpected keyword argument \'{}\''.format(
65-
funcname,
66-
next(iter(kwargs.items()))[0]))
68+
f"{funcname}() got an unexpected keyword argument '{next(iter(kwargs.items()))[0]}'"
69+
)
6770
return rv
71+
72+
73+
def process_args():
74+
"""
75+
Process the command line arguments.
76+
Now we support:
77+
- randseed: set the random seed
78+
"""
79+
for s in sys.argv:
80+
if s.startswith("--randseed="):
81+
random.seed(s.split("=")[1])

0 commit comments

Comments
 (0)