Skip to content

Commit 924f8a5

Browse files
authored
Merge pull request #559 from python-cmd2/self
Remove self from pystate if locals_in_py is False
2 parents 9ca3476 + 5d83a2a commit 924f8a5

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

cmd2/cmd2.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2982,6 +2982,8 @@ def run(filename: str):
29822982

29832983
if self.locals_in_py:
29842984
self.pystate['self'] = self
2985+
elif 'self' in self.pystate:
2986+
del self.pystate['self']
29852987

29862988
localvars = self.pystate
29872989
from code import InteractiveConsole

tests/test_cmd2.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,18 +216,35 @@ def test_base_shell(base_app, monkeypatch):
216216
assert m.called
217217

218218
def test_base_py(base_app, capsys):
219+
# Create a variable and make sure we can see it
219220
run_cmd(base_app, 'py qqq=3')
220221
out, err = capsys.readouterr()
221222
assert out == ''
222-
223223
run_cmd(base_app, 'py print(qqq)')
224224
out, err = capsys.readouterr()
225225
assert out.rstrip() == '3'
226226

227+
# Add a more complex statement
227228
run_cmd(base_app, 'py print("spaces" + " in this " + "command")')
228229
out, err = capsys.readouterr()
229230
assert out.rstrip() == 'spaces in this command'
230231

232+
# Set locals_in_py to True and make sure we see self
233+
out = run_cmd(base_app, 'set locals_in_py True')
234+
assert 'now: True' in out
235+
236+
run_cmd(base_app, 'py print(self)')
237+
out, err = capsys.readouterr()
238+
assert 'cmd2.cmd2.Cmd object' in out
239+
240+
# Set locals_in_py to False and make sure we can't see self
241+
out = run_cmd(base_app, 'set locals_in_py False')
242+
assert 'now: False' in out
243+
244+
run_cmd(base_app, 'py print(self)')
245+
out, err = capsys.readouterr()
246+
assert "name 'self' is not defined" in err
247+
231248

232249
@pytest.mark.skipif(sys.platform == 'win32',
233250
reason="Unit test doesn't work on win32, but feature does")

0 commit comments

Comments
 (0)