Skip to content

Commit f340c5b

Browse files
committed
Assert variable names are alphanumeric
1 parent 162cbb5 commit f340c5b

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

pysr/sr.py

+7
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,13 @@ def _check_assertions(
181181
raise ValueError(
182182
f"Variable name {var_name} is already a function name."
183183
)
184+
# Check if alphanumeric only:
185+
if not re.match(r"^[a-zA-Z0-9_]+$", var_name):
186+
raise ValueError(
187+
f"Invalid variable name {var_name}. "
188+
"Only alphanumeric characters, numbers, "
189+
"and underscores are allowed."
190+
)
184191

185192

186193
def best(*args, **kwargs): # pragma: no cover

test/test.py

+24-1
Original file line numberDiff line numberDiff line change
@@ -572,8 +572,31 @@ def test_sympy_function_fails_as_variable(self):
572572
model = PySRRegressor()
573573
X = np.random.randn(100, 2)
574574
y = np.random.randn(100)
575-
with self.assertRaises(ValueError):
575+
with self.assertRaises(ValueError) as cm:
576576
model.fit(X, y, variable_names=["x1", "N"])
577+
self.assertIn(
578+
"Variable name",
579+
str(cm.exception)
580+
)
581+
582+
def test_bad_variable_names_fail(self):
583+
model = PySRRegressor()
584+
X = np.random.randn(100, 1)
585+
y = np.random.randn(100)
586+
587+
with self.assertRaises(ValueError) as cm:
588+
model.fit(X, y, variable_names=["Tr(Tij)"])
589+
self.assertIn(
590+
"Invalid variable name",
591+
str(cm.exception)
592+
)
593+
594+
with self.assertRaises(ValueError) as cm:
595+
model.fit(X, y, variable_names=["f{c}"])
596+
self.assertIn(
597+
"Invalid variable name",
598+
str(cm.exception)
599+
)
577600

578601
def test_pickle_with_temp_equation_file(self):
579602
"""If we have a temporary equation file, unpickle the estimator."""

0 commit comments

Comments
 (0)