with dpg.window(label="Window"):
dpg.add_text("Hello, world")
dpg.add_button(label="Save")
dpg.add_input_text(label="string", default_value="Quick brown fox")
dpg.add_slider_float(label="float", default_value=0.273, max_value=1)
dpg.add_color_picker(label="Pick", default_value=(0, 0, 0))
This code runs without error (given the correct imports and setup)
dpg.window(label="Window")
dpg.add_text("Hello, world")
dpg.add_button(label="Save")
dpg.add_input_text(label="string", default_value="Quick brown fox")
dpg.add_slider_float(label="float", default_value=0.273, max_value=1)
dpg.add_color_picker(label="Pick", default_value=(0, 0, 0))
This code does not. A runtime error occurs on line 2. I do not understand how a with statement with no as affects the contents of the with. I've seen another similar post, but I can't understand how the explanation answers my question.
Here is the stacktrace for the error:
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\18328\PycharmProjects\sandbox\main.py", line 10, in <module>
dpg.add_text("Hello, world")
File "C:\Users\18328\AppData\Local\Programs\Python\Python39\lib\site-packages\dearpygui\dearpygui.py", line 7019, in add_text
return internal_dpg.add_text(default_value, label=label, user_data=user_data, use_internal_label=use_internal_label, tag=tag, indent=indent, parent=parent, before=before, source=source, payload_type=payload_type, drag_callback=drag_callback, drop_callback=drop_callback, show=show, pos=pos, filter_key=filter_key, tracked=tracked, track_offset=track_offset, wrap=wrap, bullet=bullet, color=color, show_label=show_label, **kwargs)
SystemError: <built-in function add_text> returned a result with an error set
On the Python side: Context managers run completely arbitrary code on enter and exit. Python doesn't force that code to do things "behind your back", but neither does it present them from doing so; so the implementation of the specific context manager at hand needs to be inspected to know why it's modifying behavior.
From a DearPyGui perspective: The C++ library that dpg backends into maintains a "container stack". Entering a container as a context manager ensures that it's on the top of your stack. When you create a new DearPyGui object that needs to be attached to a container, it refers to that stack, and attaches itself to the thing that is currently on top.
Using the translation provided by PEP-343, you can see that
with dpg.window(label="Window"):
...
is equivalent to
mgr = dpg.window(label="Window")
exit = type(mgr.__exit__)
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
...
except:
exc = False
if not exit(mgr, *sys.exc_info()):
raise
finally:
if exc:
exit(mgr, None, None, None)
You can compare the above to the fuller translation in PEP-343 to see the single line I omitted that results from the use of as.
In your examples, dpg.window(label="Window").__enter__ is called in the first example, but not in the second.
Related
I ask for help because I literally have no idea what I have to do for this. I'm bangin my head for 2 days and I have to admit that I just dont get it...
I need a script to set the view in the sequencer to
bpy.ops.sequencer.view_all() (or similarly: bpy.ops.sequencer.view_selected())
To do that I need to override the context and tell the script it has to run that command in the sequencer area, if not it will give a:
Python: Traceback (most recent call last):
File "\Text", line 4, in <module>
File "F:\MEDIA\GAMES\Steam\steamapps\common\Blender\3.4\scripts\modules\bpy\ops.py", line 113, in __call__
ret = _op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.sequencer.view_all.poll() failed, context is incorrect
..and of course just setting:
bpy.context.area.ui_type = 'SEQUENCE_EDITOR'
..does nothing
But again I have absolutely no idea what to do so, any help would be highly apreciated..
Here is the correct context override:
import bpy
# go through all areas until sequence editor is found
for area in bpy.context.screen.areas:
if area.type == "SEQUENCE_EDITOR":
override = bpy.context.copy()
# change context to the sequencer
override["area"] = area
override["region"] = area.regions[-1]
# run the command with the correct context
with bpy.context.temp_override(**override):
bpy.ops.sequencer.view_all()
break
I found a very perplexing issue in aiosmtpd/244, sharing my puzzlement here to help me find inspiration on how to troubleshoot.
Situation
Two servers running Red Hat 7.9
Works on one, doesn't work on the other
Problematic code, simplified:
>>> from aiosmtpd.controller import Controller
>>> from aiosmtpd.handlers import Sink
>>> cont = Controller(Sink())
>>> cont.start()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/aiosmtpd/controller.py", line 180, in start
raise RuntimeError("Unknown Error, failed to init SMTP server")
RuntimeError: Unknown Error, failed to init SMTP server
The above RuntimeError can only be generated if, at the end of the start() method, self.smtpd is still None.
Expected flow
start() -> _run() -> loop.create_server()
Then upon first connection:
loop.create_server() -> _factory_invoker() -> factory()
The attribute smtpd is set within _factory_invoker in these lines:
try:
self.smtpd = self.factory()
if self.smtpd is None:
raise RuntimeError("factory() returned None")
return self.smtpd
except Exception as err:
self._thread_exception = err
return _FakeServer(self.loop)
self._thread_exception is interpreted in these lines:
if self._thread_exception is not None:
raise self._thread_exception
# Defensive
if self.smtpd is None:
raise RuntimeError("Unknown Error, failed to init SMTP server")
As you can see, if self.smtpd is None, then it would only happen if there's an error in _factory_invoker(). If so, the error should've been caught and recorded in self._thread_exception. If self._thread_exception is None, then _factory_invoker() had succeeded, and thus self.smtpd couldn't be None.
My main problem in troubleshooting this is that on all my test systems (Windows, Ubuntu, OpenSUSE, MacOS, and FreeBSD), I never encountered a similar error.
So I'm stumped. I'd appreciate any ideas on solving this problem.
Okay, so apparently I was sent on a wild goose chase.
The compounding factor is because I have suppressed ALL exceptions in these lines:
try:
self._testconn()
except Exception:
# We totally don't care of exceptions experienced by _testconn,
# which _will_ happen if factory() experienced problems.
pass
As a result, a very helpful exception raised within self._testconn() was swallowed.
Apparently self._testconn() failed in its attempt to connect to the host:port, and thus _factory_invoker() never got called.
Once the try..except block is modified to only swallow socket.socket_timeout, the actual problem reared its head, and we can quickly fix it.
It's all documented in aiosmtpd/244 and thus I won't repeat them here :-)
Thank you all who spent the time & effort to try solving this puzzle!
I want to run tests with multiple builds of a product running them once. Here is example of the code:
import unittest
suite = unittest.TestLoader().discover("./tests")
runner = unittest.TextTestRunner()
for build in [build1, build2]:
get_the_build(build)
runner.run(suite)
The first iteration works well, but on the start of the second one an error appears:
Traceback (most recent call last):
File "D:/Path/to/my/folder/run_tests.py", line 9, in <module>
runner.run(suite)
File "C:\Program Files (x86)\Python36-32\lib\unittest\runner.py", line 176, in run
test(result)
File "C:\Program Files (x86)\Python36-32\lib\unittest\suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "C:\Program Files (x86)\Python36-32\lib\unittest\suite.py", line 122, in run
test(result)
TypeError: 'NoneType' object is not callable
What is happening? What result runner calls? And why does it fail? Any ideas how to solve the problem?
Well, well, well. I have spent the last hour of my life looking at the code of unittest in GitHub, which can be found here. I just went to the code of suite.py (here), one of the files in the error you are getting. This is the actual code of TestSuite.run:
def run(self, result, debug=False):
topLevel = False
if getattr(result, '_testRunEntered', False) is False:
result._testRunEntered = topLevel = True
for index, test in enumerate(self):
if result.shouldStop:
break
if _isnotsuite(test):
self._tearDownPreviousClass(test, result)
self._handleModuleFixture(test, result)
self._handleClassSetUp(test, result)
result._previousTestClass = test.__class__
if (getattr(test.__class__, '_classSetupFailed', False) or
getattr(result, '_moduleSetUpFailed', False)):
continue
if not debug:
test(result)
else:
test.debug()
if self._cleanup:
self._removeTestAtIndex(index)
if topLevel:
self._tearDownPreviousClass(None, result)
self._handleModuleTearDown(result)
result._testRunEntered = False
return result
So, basically, what this code does is to iterate over each test the suite has and invoke it:
for index, test in enumerate(self):
...
if not debug:
test(result) # This is the line throwing the error
...
As you can see, that loop iterates over the suite itself, so I it must have an __iter__ method defined somewhere. After 5 minutes of not finding it inside the class TestSuite, I realized is the parent class who has such method. This is what I found in BaseTestSuite:
def __iter__(self):
return iter(self._tests)
Basically, it just returns an iterator of the tests. In that moment, such line of code, was a high wall I couldn't surepass. But I didn't give up and went back to TestSuite.run definition and, miraculously, I spotted the next lines:
...
if self._cleanup:
self._removeTestAtIndex(index)
...
And that made me wonder: "Are the tests being removed? Let me investigate". Then I was enlightened, because inside _removeTestAtIndex I spotted this line:
self._tests[index] = None
End of story. So, after running all of your tests the first time, they got converted into nothing more than None: the list of tests inside the suite ended up being a list of Nones ([None, None, ..., None]).
So, how do you prevent such behaviour? Just turn off the _cleanup flag inside the suite. This should work:
Answer
import unittest
suite = unittest.TestLoader().discover("./tests")
suite._cleanup = False # Prevent such cleanup
runner = unittest.TextTestRunner()
for build in [build1, build2]:
get_the_build(build)
runner.run(suite)
Sorry for the long story but, besides showing you how to solve your issue, I also wanted to teach you how to debug whatever.
Let me know if this actually worked for you. Otherwise, tell me what went wrong.
Feels like a horrible hack, but making a deep copy of the suite each time before running it solved the problem for me:
import unittest
import copy
suite = unittest.TestLoader().discover("./tests")
runner = unittest.TextTestRunner()
for build in [build1, build2]:
get_the_build(build)
runner.run(copy.deepcopy(suite))
I'm attempting to make a part of a class that will allow me to create a new directory for output files each time an instance is created. However, whenever the mkdir_p function is executed I get this error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
jim = OPNprobe('oops','x','a')
File "H:/Bio_Files/Pyscripts/opsinomics/aa.pya.py", line 22, in __init__
self.mkdir_p(self.path+'\\'+self.out_name)
Empty
I only get this error if the directory hasn't been created already. Once it throws the error and creates the directory, it will then let me initiate a new instance without thowing the error again.
Here's the function I'm using to create the new directory. I'm passing the path variable from the initial variables supplied by the user. the 'path' variable is currently just 'oops', so nothing fancy and should just create a directory named oops.
def mkdir_p(self,path):
try:
os.makedirs(self.path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else: raise
Any help would be much appreciated...just getting into writing classes and I'm struggling with how to juggle variables between functions and create output files without defining the file path within each function.
I think you want to write your mkdir_p method like this:
def mkdir_p(self,path):
try:
os.makedirs(self.path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST:
pass
else: raise # pay attention here, this line must be indented the same as the 'if' line
In you original code, else is a branch for try and the code under else branch will be executed regardless whether there is an exception or not.
Besides, you'd better use os.path.join(self.path, self.out_name) instead of self.mkdir_p(self.path+'\\'+self.out_name), it will make your code more portable.
I'm attempting to fix a bug in the python package caniusepython3 which arises because distlib isn't parsing pypi projects correctly. I've written this unit test
#mock.patch('distlib.locators.locate')
def test_blocking_dependencies_locators_fails(self, distlib_mock):
"""
Testing the work around for //bitbucket.org/pypa/distlib/issue/59/
"""
py3 = {'py3_project': ''}
breaking_project = 'test_project'
distlib_mock.locators.locate.return_value = "foo"
distlib_mock.locators.locate.side_effect = AttributeError()
got = dependencies.blocking_dependencies([breaking_project], py3)
# If you'd like to test that a message is logged we can use
# testfixtures.LogCapture or stdout redirects.
So that when distlib fixes the error in the next release of distlib the test case will still be valid.
The problem is that the MagicMock never raises a AttributeError as I expected and instead returns a string representation of the magic mock object
try:
# sets dist to <MagicMock name='locate()' id='4447530792'>
dist = distlib.locators.locate(project)
except AttributeError:
# This is a work around //bitbucket.org/pypa/distlib/issue/59/
log.warning('{0} found but had to be skipped.'.format(project))
continue
And causes this stack trace later on because it returns the object repr,
======================================================================
ERROR: Testing the work around for //bitbucket.org/pypa/distlib/issue/59/
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/unittest/mock.py", line 1136, in patched
return func(*args, **keywargs)
File "/Users/alexlord/git/caniusepython3/caniusepython3/test/test_dependencies.py", line 81, in test_blocking_dependencies_locators_fails
got = dependencies.blocking_dependencies([breaking_project], py3)
File "/Users/alexlord/git/caniusepython3/caniusepython3/dependencies.py", line 119, in blocking_dependencies
return reasons_to_paths(reasons)
File "/Users/alexlord/git/caniusepython3/caniusepython3/dependencies.py", line 43, in reasons_to_paths
parent = reasons[blocker]
File "/Users/alexlord/git/caniusepython3/caniusepython3/dependencies.py", line 29, in __getitem__
return super(LowerDict, self).__getitem__(key.lower())
nose.proxy.KeyError: <MagicMock name='locate().name.lower().lower()' id='4345929400'>
-------------------- >> begin captured logging << --------------------
ciu: INFO: Checking top-level project: test_project ...
ciu: INFO: Locating <MagicMock name='locate().name.lower()' id='4344734944'>
ciu: INFO: Dependencies of <MagicMock name='locate().name.lower()' id='4344734944'>: []
--------------------- >> end captured logging << ---------------------
Why is the MagicMock not returning an exception when distlib.locator.locate() is called?
Update: I was able to get this unit test to work when I switched to using
def test_blocking_dependencies_locators_fails(self):
"""
Testing the work around for //bitbucket.org/pypa/distlib/issue/59/
"""
with mock.patch.object(distlib.locators, 'locate') as locate_mock:
py3 = {'py3_project': ''}
breaking_project = 'test_project'
locate_mock.side_effect = AttributeError()
got = dependencies.blocking_dependencies([breaking_project], py3)
# If you'd like to test that a message is logged we can use
# testfixtures.LogCapture or stdout redirects.
But I'm still wondering what I did wrong with the decorator format.
When you use #mock.patch, it mocks what you tell it, and passes that mock object as a parameter. Thus, your distlib_mock parameter is the mock locate function. You're effectively setting attributes on distlib.locators.locate.locators.locate. Set the attributes directly on the provided mock, and things should work better.
#mock.patch('distlib.locators.locate')
def test_blocking_dependencies_locators_fails(self, locate_mock):
# ...
locate_mock.return_value = "foo"
locate_mock.side_effect = AttributeError()
# ...