Thursday, July 10, 2014

New Python profiler UI

So, I wanted to show what I have so far on the profiler front.

Below is its main UI (on a dark palette -- kudos to Qt which makes this pretty easy to do):



The tree shows the attached processes and the CPU tab shows data for the CPU from the process which is being analyzed.

Based on that, it's possible to select a timeframe where stack info is shown (in this case the profiler is analyzing itself). Clicking on a stack opens an internal editor (which can only view the file so far) at the proper place (but the idea is that in the future it'll open the editor in your preferred editor/IDE).

It's possible to start/stop the sampling and the stacks can be grouped either by line or by methods.

Another thing (which is also still incomplete) is provide a view which will show a profile session view graphically... Below is a snapshot of the work on that front so far.



The work is still very much in the beginning, but the sampling view should be usable already -- the plan is to release  the first builds some days after the crowdfunding finishes... thank you to all who are helping to make this possible: https://sw-brainwy.rhcloud.com/support/pydev-2014

Tuesday, June 24, 2014

PyDev 3.6.0 released

PyDev 3.6.0 was just released.

The really major change in this release is that PyDev updated its internal Jython to the latest version, which also allowed PyDev to update its support to the latest pep8.py.

Also, following this, autopep8.py was also integrated (although it seems there's still an issue dealing with non-ascii files -- see: https://sw-brainwy.rhcloud.com/tracker/PyDev/402 for a workaround). Note that unlike pep8.py, autopep8.py doesn't really use the internal Jython (it runs based on the default configured Python interpreter). This is mostly because Jython was too slow when running it (annoyingly so in this use-case), so, there's only the option of running autopep8.py externally.

Also, some 'nice to have' features were added:

Shift+F9 will run the current editor directly in debug mode -- so, no need to Alt+R+G, 1-4 for that anymore :)

Also, when selecting a unit-test to run (Ctrl+F9), if Shift is pressed when the test(s) to run is selected, it'll also run in debug mode (previously it was almost mandatory to create a regular run selecting the tests, killing it and pressing F11 just to re-run the last test in debug mode).

Besides this, there were some bug-fixes (and for those using LiClipse: http://brainwy.github.io/liclipse, it's already updated with the latest PyDev version -- and now it supports launching for other languages and Julia support was added).

Enjoy!

p.s.:  Thank you for all that are supporting the PyDev crowdfunding: https://sw-brainwy.rhcloud.com/support/pydev-2014/

Tuesday, May 20, 2014

PyDev 3.5.0 released

PyDev 3.5.0 is now available...

The main feature in this release relates to improvements to work with py.test (note: those that want to use it have to enable it in the PyUnit preferences -- besides having to install it properly in the used Python installation).

Mainly, the integration was changed so that the py.test xdist plugin can be properly used and module/session scoped fixtures should also work properly. The PyUnit UI in the preferences was also changed to show the preferences related to py.test when it's shown.

Still, there are other improvements: the Model.objects from django 1.7 is now available on code-completion again (as the static analyzer couldn't cope with it there are workarounds in the code), private attributes (those starting with '__') are now shown when hovering over it on the debugger and there's a bunch of other bug-fixes and minor features available (see http://pydev.org for details).

Also, for those that don't know, there's an ongoing crowdfunding to keep PyDev support going on: http://tiny.cc/pydev-2014...

Thursday, May 15, 2014

Crowdfunding for PyDev and new Python profiler UI (for any IDE)

Ok, I just started a crowdfunding project (at http://tiny.cc/pydev-2014) for the continued development of PyDev and the creation of a new profiler UI.

This is actually the 2nd crowdfunding for PyDev after Appcelerator stopped supporting it. Last year a similar crowdfunding allowed me to keep on developing PyDev until now, as well as creating a new PyDev/Eclipse bundle called LiClipse, which added lightweight support for several languages as well a dark theme inside Eclipse.


So, now I'm reaching out again for the PyDev community to allow me to keep on developing PyDev and shaping the Python landscape.


This year when planning what to do and filtering on existing requests, one of the things that stood up was providing proper support for profiling in PyDev.


After tinkering with the idea a bit and trying to find out how I think would be the best way for this workflow, I've settled on creating a separate tool and then integrating it properly in PyDev... not only this approach will allow Pythonistas that don't use PyDev to have a nice profiling companion, but I think it'll also yield better results than doing it all inside of Eclipse -- besides, I'll be able to do it all in Python!


So, this is the main feature I've planned for this year, but there are others too which are more focused on PyDev itself, such as having preferences per-project, migrating to a new workspace, validating docstrings for its type on a test run, external pep8 linter, vertical lines for indentation, attach debugger to running process -- besides the usual bugfixing and support.


So, please help in funding (and sharing) at http://tiny.cc/pydev-2014 to help in making the new profiler UI a reality and to keep PyDev going strong!



Friday, March 28, 2014

Mastering writing code on PyDev

One of these days I was pair coding with a friend -- which was also using PyDev -- and upon looking him code I realized that there are some simple things which everyone should know when writing code on PyDev:

1. Want to write a new line? Use Shift+Enter: This is what I almost always use in PyDev instead of the plain enter to enter a new line.

How it works: It'll emulate moving to the end of the line and pressing enter there.

Tip: It can be used when there's a completion to avoid applying it while going to the next line (as Enter is also used to apply a completion if you don't use Shift+Enter you have to press ESC before to avoid applying it if you use a plain Enter).

2. Want to copy or move some lines? Ctrl+Alt+Up will copy the lines up and Ctrl+Alt+Down will copy them down and then Alt+Up or Alt+Down can be used to move them up or down (so, it's a line-oriented copy/paste which is really handy).

3. Is there a string or comment which is too big and you want to wrap it? Use Ctrl+2, W and it'll wrap it for you (using the number of columns assigned in the print margin preferences).

4. Want to create a docstring for the parameters of a method? Ctrl+1 -> Make Docstring (in a line with the method declaration).

5. Assign parameters to variables? Ctrl+1 -> Assign parameters to attributes (in a line with the method declaration in a class). Alternatively use Ctrl+2, A.

6. Want to select the current word? Shift+Alt+Up will select the current word for you (and if you keep using Shift+Alt+Up it'll then select the enclosing context and Shift+Alt+Down will deselect it again).

7. Rectangular selection: Shift+Alt+A.

8. Want to rename a local token? To do that use Ctrl+2, R (note that for renaming a token in multiple modules you'd use Shift+Alt+R or a package/module in the PyDev Package Explorer would be renamed with F2).

9. To rename something that's not a token (such as a comma) -- if you're in LiClipse (which adds this feature) -- you can do Ctrl+K (or Ctrl+Shift+K to go backwards) multiple times to mark the places you want to rename and then go on to rename it (as a note, Ctrl+Alt+K will unlink one of the occurrences). This can also be used for a substring -- or any character combination for that matter.

10. Do you have some code with multiple tokens that are not found and need to be imported? Ctrl+Shift+O can be used to resolve the multiple missing tokens. Alternatively you could also use Ctrl+1 on a line with a missing import to get the suggestion to add it (if it wasn't already added in a code-completion which added it for you automatically).

11. Like TDD coding? i.e.: write the test first and do the code later. If so, you can usually write the test and use Ctrl+1 to provide a suggestion to create the missing method, module or attribute.

12. PyDev doesn't automatically re-analyze dependent modules when one module changes, so, I've seen people just add some space and save the file again just to force a new code analysis... while this works, there's a specific keybinding: Ctrl+2, C which will force a code-analysis in the current module.

13. When there are many contiguous lines commented and you want to uncomment them, do you see yourself selecting all those lines to uncomment it? Did you know that Ctrl+5 does that promptly for you from any line of that block?

14. Just edited something but don't remember where it was? Ctrl+Q can be used to go to the last place you edited some code.

15. Do you have some code you just copied from somewhere and want to create a module with it? Go to the PyDev package explorer and just paste the code there to create a new module with those contents.

16. Do you have some method call or variable that you want to add to another local variable or field? Use Ctrl+1 (on a line that still doesn't have an assign) and choose assign to local or assign to field.

Besides those tips, print the bindings from: http://pydev.org/manual_adv_keybindings.html and leave it by your side until you don't master them :)

Thursday, March 20, 2014

PyDev 3.4.1: improved interactive console, multiprocess debugging

One of the major features added is that now F2 can be used to send the current line to the interactive console (or the current multi-line selection).

It's close to what was previously used as Ctrl+Alt+Enter, but with some differences:

1. It'll fix the indentation of the code when sending things to the console (so, you shouldn't have syntax errors because of the indentation when using Ctrl+Alt+Enter).

2. When a line is sent, the cursor goes to the next line (this may seem minor, but it's a huge time-saver and makes things much smoother).

3. It's a single keypress! (and that was really hard to decide as all keys seem to be taken -- even F2 -- but I think that F2 as it was before wasn't very useful).

All in all, if you're into doing things interactively, things are nicer with F2.

Note: Ctrl+Alt+Enter can still be used to do an execfile, but aside from that, F2 is the preferred way to send contents to the console.

Credit goes to Ed Catmur and James Blackburn for this feature -- I just integrated it :)

Another major feature is that the debugger now works properly when debugging multiple processes (and when a launch is terminated it'll also kill all subprocesses). This means the previous patch the debugger did to Django is no longer needed... Just F11 to relaunch your last launch and debug multiple processes!

Major feature #3: Ctrl+F9 (which opens a dialog for selecting which tests to run) now works properly with py.test too -- even if tests are not under class.

Major feature #4: pxd and pxi Cython files are now properly handled.

And as the last thing, which isn't an actual feature, but something noteworthy: PyDev no longer changes the default encoding (i.e.: sys.setdefaultencoding). Back when PyDev started to do that (in Python 2.4 I believe) there wasn't much choice to see unicode contents properly in the console, so, PyDev changed the default encoding to be the encoding of the console. Fast forward a bit and Python now provides a way to set the sys.stdout/stderr encodings through PYTHONIOENCODING (Python 2.6 onwards), so, PyDev now only sets that variable and no longer changes the default encoding (the main issue there is that when some application was later deployed, it could have a different default encoding and things could break because of UnicodeDecodeErrors).

Note that this is not all, other things were done too... See: http://pydev.org/ for details -- and note that LiClipse: http://brainwy.github.io/liclipse/ is already updated to the latest PyDev too.

Sunday, March 02, 2014

Should the Python garbage collector be disabled?

Ok, though question... so, first a little bit of background:

The Python garbage collector is useful for collecting reference cycles, but objects are collected by default when their reference count reaches 0, so, most of the time objects will be collected properly and the collector is only useful when you have a cycle.

Also, there's no guarantee when it'll bump in to do a collection, so, if you're doing UI programming (i.e.: using something as Qt), and you use multiple threads, if you have a cycle, it's possible that the cycle is broken on a collect out of the main thread, which can cause your application to crash if an UI object is collected!

In this case, even if you're careful about collecting things, there's always the case where you have an exception and the object goes to sys.exc_info and becomes alive for much more time than you'd intend, so, if you are using an UI framework, at least making sure that you only collect in the UI thread is a must (see below code which helps doing that).

So, personally, I think that in Python the garbage collector should always be turned off (which can even make your code a lot faster in many situations) and the gc module should be used as a debug tool to find cycles which may occur -- and those should be treated as application errors!

weakref.ref() is one of the most useful things for breaking the cycles and if you need references to methods use a WeakMethodRef: http://code.activestate.com/recipes/81253/

Below is some code to make manual garbage-collection (credit to Erik Janssens) -- while developing the method check() should usually return self.debug_cycles() -- if you want you can use the remaining code to leave as a tool to break cycles in a real application if you want to play safe (although I think disabling it altogether is better if you make sure you don't have cycles) ...

Also, while we're talking about cycles and garbage collection, make sure you never override __del__... Python has an optional callable in weakref.ref() which can be used to do things when an object is collected -- and which doesn't have the problems related to __del__.


class GarbageCollector(QObject):
    '''
    Disable automatic garbage collection and instead collect manually
    every INTERVAL milliseconds.

    This is done to ensure that garbage collection only happens in the GUI
    thread, as otherwise Qt can crash.
    '''

    INTERVAL = 10000

    def __init__(self, parent, debug=False):
        QObject.__init__(self, parent)
        self.debug = debug

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.check)

        self.threshold = gc.get_threshold()
        gc.disable()
        self.timer.start(self.INTERVAL)

    def check(self):
        #return self.debug_cycles() # uncomment to just debug cycles
        l0, l1, l2 = gc.get_count()
        if self.debug:
            print ('gc_check called:', l0, l1, l2)
        if l0 > self.threshold[0]:
            num = gc.collect(0)
            if self.debug:
                print ('collecting gen 0, found:', num, 'unreachable')
            if l1 > self.threshold[1]:
                num = gc.collect(1)
                if self.debug:
                    print ('collecting gen 1, found:', num, 'unreachable')
                if l2 > self.threshold[2]:
                    num = gc.collect(2)
                    if self.debug:
                        print ('collecting gen 2, found:', num, 'unreachable')

    def debug_cycles(self):
        gc.set_debug(gc.DEBUG_SAVEALL)
        gc.collect()
        for obj in gc.garbage:
            print (obj, repr(obj), type(obj))