• Sérgio Silva
    Este é um vídeo muito interessante do Raymond Hettinger, onde a beleza do código escrito em Python está bem patente. É um vídeo onde o Raymond explica de forma bem divertida como transformar o nosso código, que muitas vezes sofre dos vícios de outras linguagens, num código mais "bonito" e pythónico.

    Uma das razões por que gostei imediatamente do Python, mal tive contacto com esta linguagem de programação, foi o facto de ser uma "linguagem" muito simples que dá a primazia a um código fácil de ler e de perceber, e é por isso que digo que o Python é bonito.

    Vejam a seguir o vídeo inspirador "Transforming Code into Beautiful, Idiomatic Python" do Raymond Hettinger.


    Ver post completo

    Por Sérgio Silva

    "O Python é bonito e tem Zen" é um post originalmente publicado no blog Em Python

  • Diogo Mónica


    Por diogomonica, em 1 Novembro 2013 23:00 - Mais entradas deste utilizador
    a little bit more about myself
  • Diogo Mónica
    My blurb, who I am and where I come from.
  • When I explained how the Leap Motion device could be used on Fedora 19, I mentioned how I had one of those early prototypes. Well, Leap Motion was extremely kind and sent me an actual device as a thank you for starting the thread asking for Linux support. Now that GUADEC is over and I am spending my vacation in Portugal, I had a little time to play with my fancy new device and wrote a relatively small script to control GNOME with it. I call it the über original name of: Leap GNOME Controller!

    For those who don’t care about technical details, here’s the video showing what can be done with Leap, GNOME and this script. Technical details follow below the video:

    The two videos that compose the one above were recorded with an HD camera and GNOME Shell’s screencast recorder. I tried to sync them the best I could but a certain delay can be noticed, especially at the end of the video.

    The code

    Leap Motion provides a “close source” shared library and a high-level API with the respective documentation for the many bindings it has. To code it quickly, I used the Python bindings and Xlib to fake the input events.

    Leap Motion’s APIs make it really easy for one to simulate a touch-screen. It even offers a “screen tap” gesture that should be the obvious choice when mapping a finger touch/tap to a mouse click. However, this didn’t work very well. The problem is that if we are tracking one finger to control the mouse movement, when performing the “screen tap” gesture, the finger (and mouse) will of course move. Making it as frustrating as seen on ArsTechnica hands-on video.

    I came up with a solution for this by dropping the “screen tap” gesture and using the “key tap” instead. The “key tap” is a simple, quick down-and-up finger movement, like pressing a key. This is much more precise and easier for a user to do than the “screen tap”. Of course that when the finger moves for performing the gesture, the mouse pointer would move as well, so I came up with a little trick to work around this: when the mouse pointer doesn’t move more than a couple of pixels for half a second, it will stop and only move again if the user makes it move for more than 150 pixels. This allows for the user to stop the pointer with precision where it needs to be and perform the gesture without making the pointer move.


    The Leap device offers a lot of possibilities for adding many gestures. Ideally they should be implemented per application but being able to control the shell is already pretty useful, so it would be wonderful to fine-tune the current gestures and add new ones. I also wish the library’s source code were open because I ran into small issues and I wish I could take a look at the source code, instead of trying to fix it based on the theories of what might be wrong.

    I haven’t explored the AirSpace appstore yet so I don’t know if it is worth adding (or possible to add) this script there but I will check it out.

    Have fun with Leap and GNOME!

  • Sérgio Silva
    Um guia rápido de programação em Python para quem se está a iniciar nesta linguagem ou para quem quer rever ou aprofundar conhecimentos em algumas matérias.

    Link: Python - Quick Guide

    Guia rápido
    Sem dúvida um link para manter nos nossos favoritos.

    Ver post completo

    Por Sérgio Silva

    "Guia rápido de programação em Python" é um post originalmente publicado no blog Em Python

  • Goncalo Gomes

    ## exploration and discovery
        from PriorExperience import insight,serendipity
        my_new_idea = gen_ideas(insight,serendipity,NewTechnology)
        my_new_idea = copy.copy(somebody_elses_idea)
    ## get funding and build a team
    funded = False
    while not funded:
        proposal = gen_proposal(my_new_idea).submit()
        funded = proposal.was_funded
    from multiprocessing import Pool
    grads = Pool(5) ; postdocs = Pool(3) ; undergrads = Pool(8)
    ## do the work and write it up
    results = get_data(grads,postdocs,undergrads,
    paper = results.write_paper()
    paper.submit(journal="Science") # this will be accepted without revision
    ## reap rewards
    cv_item = collect_prize(type="Nobel",thank=",".join([ for x in grads]))

    Original GitHub repository here.

  • Sérgio Silva
    Recentemente tive a necessidade de atribuir o valor de uma variável numa expressão if em Python, para evitar que um determinado código fosse executado duas vezes.

    Expressão If

    Supondo que temos o seguinte código.

    Ver post completo

    "Atribuição de variável numa expressão If em Python" é um post originalmente publicado no blog Em Python

  • Sérgio Silva
    Olá pessoal. Criei um novo blogue, dedicado à linguagem de programação Python no endereço Removi deste blogue os posts sobre Python e passei-os para o novo blogue. Os links dos antigos posts sobre python estão a reencaminhar para o novo endereço no blogue

    Ver post completo

    "O meu novo blogue sobre Python" é um post originalmente publicado no blog Sergio Silva Blog

  • Sérgio Silva
    Olá a todos.

    Depois de ter lançado o meu blogue pessoal, no endereço, dedicado principalmente à programação e às tecnologias de informação, decidi agora criar um blogue exclusivamente sobre a linguagem de programação Python, o

    Pontapé de saída

    Passei todos os posts que escrevi sobre Python, no meu blogue pessoal (Sergio Silva Blog), para este blogue (


    Ver post completo

    "Pontapé de saída" é um post originalmente publicado no blog Em Python

  • Goncalo Gomes

    One of the many great advantages of python is introspection. Python’s introspective design allows you to read, modify, write (and in some cases call) the functions, objects, variables defined in the current running instance of python. Amongst other things it allows for your programs to do smart things such as listing all methods and properties of an object instance, obtaining a list of frames and accessing your call stack.

    One such case I needed to use introspection was in a debug function where I want it to print who the caller is, so that if I get a flood of debug messages, I know what their caller was. For my own needs, I don’t need to be specific as to the frame address because I know each parent would only have a single call to my debugging function, I just can’t tell which order they would be calling in due to the dynamic nature of my program.

    That said, there is a simple way to do this. Python comes bundled with an extensive library of modules, one of which is the inspect module. This module defines a function called stack which returns a list of records for the stack above the caller’s frame, where 0 is the parent function to your inspect.stack() call and -1 (which is an alias to the last item in a list) is the <module>, or the bare python interpreter prior to __main__. The return list is essentially a list of record frames packed as tupples. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.

    import inspect
    def foo():
    def main():
    def debug(x):
        print "caller=%s :: %s" % (inspect.stack()[1][3], x)
    if __name__ == '__main__':

    The output is as follows:

    $ python
    caller=foo :: starting...