Using DRAKON with python's try: except: exceptions - python

Is anyone familiar with DRAKON?
I quite like the idea of the DRAKON visual editor and have been playing with it using Python -- more info: http://drakon-editor.sourceforge.net/python/python.html
The only thing I've had a problem with so far is python's try: except: exceptions. The only way I've attempted it is to use branches and then define try: and except: as separate actions below the branch. The only thing with this is that DRAKON doesn't pick up the try: and automatically indent the exception code afterwards.
Is there any way to handle try: except: in a visual way in DRAKON, or perhaps you've heard of another similar visual editor project for python?
Thanks.

You could put the whole "try: except:" construct inside one "Action" icon like this:
Both spaces and tabs can be used for indentation inside an icon.

There are limitation exist in Drakon since it is a code generator, but what you can do is to re-factor the code as much as possible and stuff it inside action block:
try:
function_1()
function_2()
except:
function_3()
Drakon works best if you follow suggested rules(skewer,happy route,branching etc).
Once you construct algorithm base on this, it can help you solve complex problems fast.
Hope thats help.

Related

Python Try-Except vs If-Else performance

Someone recently said to me "In Python it is better to try and ask for forgiveness later instead of begging for permission" which I found quite funny but also relates to my question
I'm creating a personal assistant of sorts called Ada and was being pedantic about performance. From what I gather, using a try statement is faster when it works then checking and then executing. E.G: (The second one being slower if the directory DOESNT EXIST???)
import os
try:
os.makedirs("Test")
except FileExistsError:
pass
# VS
if not os.path.exists("Test"):
os.makedirs("Test")
So when creating coding, you need to weigh up whats more likely. In my example it would be the file is more likely to NOT exist so I should use a try block which yields better performance then an If-Else
I was wondering if this is of any benefit to try (pun intended) this method of the default If-Else?
P.S (This question isn't a duplicate of Python if vs try-except since that's not specifying about comparing the probabilities of the try: code block)
My current code if anyone's interested: (Created a folder in AppData called Ada where a Config.ini file is made)
import os
AppDataDirectory = os.getenv("AppData")
AdaDirectory = AppDataDirectory + "\Ada"
ConfigFile = AdaDirectory + "\CONFIG.ini"
try:
File = open(ConfigFile, "r")
except FileNotFoundError:
try:
os.makedirs(AdaDirectory)
except FileExistsError:
print("Config File Missing")
# Setup Config File
The performance of try vs. if-else depends.
Generally, it is considered more pythonic to use try blocks because:
You do an action
If it fails then do something else
The benefit here is that if the action fails you can specify an exact error and react accordingly or keep the exception at the Base Exception class.
Using if-else isn't necessarily non-pythonic but with them python (this gets longer if there are elif statements),
Checks the boolean value of a statement
If boolean value is desired, then perform another action
If boolean value is not desired then do something else
Ultimately try blocks are recommended because you do something and specify an exact response if the action fails as opposed to setting up a variety of conditions.
A real time use case example of try-catch && if-else with Django:
I created a custom user model in account app. So if i try to import it from default user model like.
from django.contrib.auth.models import User
I will get a error like:
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'account.User
and this will hang the process.
#from account.models import User # this is the correct import
if User.objects.filter(username="milon").exits():
print(f"Super User with username {env('SUPER_USER_NAME')} is already exit!!")
else:
superuser = User.objects.create_superuser(
username="milon", email="alim.abdul#gmail.com", password="******")
superuser.save()
But if I use try-catch block.
try:
superuser = User.objects.create_superuser(
username="milon"), email="alim.abdul#gmail.com", password="******")
superuser.save()
except IntegrityError:
print(f"Super User with username {env('SUPER_USER_NAME')} is already exit!!")
except Exception as e:
print(e)
We will get bellow error and this will not hang the process.
Manager isn't available; 'auth.User' has been swapped for 'account.User'
This example was tried in docker where i was used django & react separate project in docker container. For if-else docker was hanged the other processes. But using try-catch others process was not hanged in docker container.

Which exception should I throw if a module is not the correct version?

This may have been asked before or I may be overly pedantic, but my own searches have come up empty.
Looking through the Python 2.x exceptions page, I'm not sure which one I should raise if my script determines that the __version__ of a module that's been imported, e.g. cv2, is not the correct version. For example, a script I'm working on requires OpenCV version 3; what's the best exception to raise in the following block if it determines that the version != 3?
import cv2
if not cv2.__version__.startswith('3'):
raise ValueError('OpenCV _3_ required')
You can create you own custom exception if the existing ones don't suffice.
class VersionError(Exception):
def __init__(self, msg):
Exception.__init__(self,msg)
You've got a lot of options depending on what you want to do with this exception... Generally, I'd expect the install scripts to handle setting up the appropriate versions of dependencies so I might think of this as a simple runtime assertion -- Therefore AssertionError may be appropriate.
This one is really nice -- You don't need an if statement, just an assert:
assert cv2.__version__.startswith('3'), 'OpenCV _3_ required'
My next bet would be to use RuntimeError as that is really meant to be a general exception that happens at runtime (and isn't usually meant to be caught)... It's a pretty general "Oh snap, something bad happened that we cannot recover from. Lets just spit out an error to let the user know what happened".

how to make python ignore the -tt option

First of all, I want to apologize for even trying to do this. I know that it's not recommended in any way. However, external constraints leave me little other choice than to go this path.
I have a piece of python code that lies on a read-only filesystem. I cannot move it. I cannot modify it. It has an inconsistent use of tabs and spaces. And I need this code to be importable with the -tt option.
Is there any way to ignore the -tt option for a specific import statement, a specific code section, or a certain application altogether?
I fully admit that this is a horrible, horrible solution. I await the downvotes:
dodgymodule.py:
def somefunc():
print("This is indented using 4 spaces")
print("This is indented using a tab")
main python script, which uses autopep8 to fix the code and import the resulting string instead:
import autopep8
import imp
try:
import dodgymodule
except TabError as e:
with open(e.filename, 'r') as f:
new_module_contents = autopep8.fix_code(f.read())
dodgymodule = imp.new_module('dodgymodule')
exec(new_module_contents, dodgymodule.__dict__)
dodgymodule.somefunc()
python3 -tt script.py prints out the lines, as hoped.

How should I indicate that a test hasn't been written yet in Python?

I'm doing TDD using Python and the unittest module. In NUnit you can Assert.Inconclusive("This test hasn't been written yet").
So far I haven't been able to find anything similar in Python to indicate that "These tests are just placeholders, I need to come back and actually put the code in them."
Is there a Pythonic pattern for this?
With the new and updated unittest module you can skip tests:
#skip("skip this test")
def testSomething(self):
pass # TODO
def testBar(self):
self.skipTest('We need a test here, really')
def testFoo(self):
raise SkipTest('TODO: Write a test here too')
When the test runner runs these, they are counted separately ("skipped: (n)").
I would not let them pass or show OK, because you will not find them easily back.
Maybe just let them fail and the reason (not written yet), which seems logical because you have a test that is not finished.
I often use self.fail as a todo list
def test_some_edge_case(self):
self.fail('Need to check for wibbles')
Works well for me when I'm doing tdd.

Is there a better way to check Python code for a syntax errors without external modules?

As the title says, is there a better way to check a Python source for syntax errors without the use of external modules?
I mean, in sense of a more Pythonic style or a more performant way.
def CheckSyntax(source, raw = False):
lines = source.count("\n")
source += "\nThis is a SyntaxError" # add a syntax error to source, it shouldn't be executed at all
try:
exec source in {}, {}
except SyntaxError, e:
if e.lineno != lines + 2:
if raw:
return e
else:
return e.lineno, e.offset, e.text
EDIT: Ideally it would be performant enough for real-time syntax checking.
exec doesn't sound like a particularly good idea. What if the script in question has side effects (e.g. creates or modifies files) or takes a long time to run?
Take a look at the compile function and the parser module.

Categories