Category Archives: Python
Truco de Python, como crear objetos “flojos” (Lazy objects)
Este es un “re-post” en español de este otro articulo que escribí en inglés: Python trick: How to make lazy objects?. Si ya leíste aquel articulo igual te invito a que leas este, compares y compartas.
Esta vez voy a hablar de los “lazy objects”, los he llamado así porque son mas o menos similar a lo que usaba con los “Lazy treeviews” en GTK donde el árbol muestra los expansiones pero no se cargan los nodos hijos hasta que expandes el nodo. Lo que quiero entonces es crear objetos que sirvan para contar, que tengan un tipo de dato, pero que no carguen nada de datos hasta que se necesite.
Create user interfaces with Qt for Python | The official Python bindings for Qt – YouTube
Awesome!
Podría la popularidad de Python ser superior a la de JavaScript en 5 años?
Respuesta corta: NO
La cuestión es que JavaScript está presente como bien dice el articulo, en cerca del 95% de los sitios web en el mundo, es un lenguaje de programación que domina la forma en la que las paginas web tienen cierto dinamismo, vaya, para nadie es raro escuchar de la tripleta HTML5+CSS+JavaScript, sin embargo otras tecnologias como Flash o Java decayeron tanto que solo un par de navegadores lo soportan aún.
Python por otro lado es un lenguaje de uso general, muy popular en el backend y en aplicaciones de Machine Learning y computo científico, es su sencillez y madurez lo que le da su popularidad, sin embargo no cuenta con esa exclusividad que tiene JavaScript.
Es JavaScript un mejor lenguaje que Python?. Lo dudo mucho, hay muchos ejemplos de lo que está roto en JavaScript, tanto que hasta juegos sobre sus patrones de igualdad hay. Incluso hay lenguajes que se compilan a JavaScript para hacer las cosas mas “sencillas” y menos susceptibles a errores. Sin embargo, como dije en el párrafo anterior, JavaScript cuenta con esa exclusividad en la web que hace casi imposible que otro lenguaje de programación sea tan popular como él. Si vas a aprender a hacer sitios web tienes por fuerza que aprender a usar JavaScript, incluso si usas algún framework. Otro punto fuerte de JavaScript son los dispositivos móviles, para muchos el tener que mantener la misma app en diferentes plataformas los ha llevado a tener un framework con un lenguaje de programación común, ahí es donde JS ha sido el que ha triunfado, es común encontrarse frameworks que usan JS y “convierten” estas instrucciones a una app nativa, o en el peor de los casos a una especie de web-view con el dinamismo dado por JS.
Como podría Python ganarle terreno a JavaScript?, lo está haciendo muy bien sirviendo desde el backend (como de costumbre), muchos sitios web estan construidos sobre Django, APIs que se han construido sobre Flask, en el computo científico es muy pero muy popular, pero seria genial que Python fuera la base para alguna plataforma móvil, te imaginas escribir apps para dispositivos móviles usando Python de forma nativa? es decir, que el dispositivo use Python directamente, que no se compile a JS, Java/Kotlin u ObjectiveC/Swift.
Cuál es tu predicción a 5 años?, Python será mas popular que JavaScript?.
JavaScript and Python are two influential programming languages for building a wide range of applications.
Source: Could Python’s Popularity Outperform JavaScript in the Next Five Years?
Python no tendrá Master/Slave en 3.8
Guido van Rossum hizo el merge del PR de Victor Stinner, por lo que los términos Master y Slave ya no aparecerán en la versión 3.8 de Python, aunque uno de los PRs quedó fue porque refleja la terminología de las pseudoterminales de UNIX.
Así que váyanse preparando, para eliminar los “child processes” porque como vas a tener a un niño trabajando. Igual los Daemons, y finger tendrá que ser renombrado porque, pues propone un dedo y no se me vayan a ofender por eso…
De saber que te marchitas no te corto florecita…
Remover “Master” y “Slave” de Python?
A ver que opina usted, ¿le gustaría que se dejaran de usar los términos “master” y “slave” o “Maestro” y “Esclavo” de la terminología en Python?.
En lo personal creo que hay muchas cosas mejores que hacer, un par de palabras que no me parecen en absoluto ofensivas porque desde un principio, no estan dirigidas a mi, no se refieren a mi, de hecho, no se refieren a una persona, se refieren a un par de procesos.
Me da un poco de coraje mezclado con tristeza el hecho de que haya personas que con cosas tan triviales como un par de palabras se sientan ofendidas, deberían entender que son solo palabras, las palabras sin contexto no tienen un verdadero significado y dentro del contexto en Python solo se refiere a un proceso que tiene el control sobre otro que no, lo que dice que no es el maestro y el otro el esclavo.
Documentando código en Python
Code is more often read than written
– Guido Van Rosssum
Buenas practicas en Django
Aquí no hay mucho que decir, estamos hablando de Python y por lo tanto aplican las reglas de estilo de Código de Python, debes escribir siguiendo la PEP8. Django también tiene sus propias convenciones para escribir código, estas las puedes encontrar aquí , coteja con las de Python, verás que son complementarias.
Tips and tricks: Django – Mostrar cierto contenido seleccionado en un ChoiceField
Si hemos usado Django seguro nos hemos enamorado de su forma de hacer formularios, sobre todo los que están relacionados con un modelo, puesto que son simplísimos. Hay que reconocer lo simple de Django, y gracias a esta simplicidad que no busca satisfacer completamente todas las necesidades podemos encontrarnos con situaciones que pues, no se apegan a lo que queremos hacer.
Buenas prácticas en Python
Programar es divertido, sobre todo si tienes a tus manos el lenguaje de programación y otras herramientas de tu elección, sin embargo, a veces cometemos errores que bien fácil podemos evitar si seguimos estas buenas prácticas.
Lo nuevo en Python 3.7
Python, continua con su desarrollo y aunque en la versión 2.7 ya no tiene grandes cambios si que lo tiene en la versión 3, en esta ocasión la versión 3.7 que incluye una cuantas cositas que si que valen la pena mencionar.
Python is growing up, you know that because tools are getting better
Microsoft, a company that have their very own tools and programming languages is now making it easier for developers to use their favorite language. This time Python have better support in the Visual Studio Code, more specifically in the IntelliSense autocomplete System.
Visual Studio Code is the source code editor that Microsoft released as Open Source and is available in Linux, Windows and MacOS. and thanks to the Python Language Server now have better support for Python. I mean, Python support has been there for a while, but is greatly improved by the PLS.
Do you use Python or Visual Studio?, leave your thoughts in the comment section.
Python Language Server an option for those that code
Source: Microsoft Visual Studio Code replumbed for better Python taming • The Register
GitHub adds Python support for security alerts – Help Net Security
This is good, as a developer is a PITA to follow all the dependencies your app have. There are several tools to keep them up to date (updating your requirements.txt file) for future builds/updates of your app. But sometimes we just don’t follow the security flaws.
GitHub’s Security Alerts now also work for Python projects, notifying developers about vulnerabilities in software packages that their projects depend on.
Source: GitHub adds Python support for security alerts – Help Net Security
Surprise surprise, Python best programming language according to Linux journal
Not that I’m surprised, Python is in humble opinion the best balanced programming language, it is really general purpose pl doing from simple automation scripts to complex projects and scientific computing.
Java, JavaScript, C#? No, Python is the fastest growing programming language | ZDNet
There is a reason for that. Python is
- Simple, easy to read, easy to write; then, easy to learn
- Powerful with all that bunch of packages/modules included and all others created by the community freely accesible with a simple
pip
call. - All purpose, use to automize something, use it to run a web site, an API, even to create desktop apps.
- Multi-platform, Windows, Linux, Mac, BSD’s, even in embedded systems.
- Fast enough,
You can find some of those in another languages, but not all achieve that.
Python is now the fastest-growing major programming language, according to Stack Overflow.
Quick tip when using vagrant+django
I started to use vagrant to hold my development environment, it helps to keep the development environment isolated, since the app will run on a Linux server, with a specific database engine and probably some other specific modules, I don’t want to clutter my OS with all that stuff. More if I plan to work on another project that maybe, have a dependency on other versions of the same base (legacy Django perhaps?)
(Reblog) HotKeys on Windows using Python
This post comes from the old blog.
A few weeks ago, I have to write a program in PyGTK that was supposed to be all the time in the background. This application needs to run over Microsoft Windows, and hide in the notification area, wich in Windows is near to the clock.
One of challenges for me in this application is that as it must run in the background there must be a way to raise it, the most easy way to do it is by force the user to click on the small icon in the notification area, but in this case, that was impossible because the computer don’t have any mouse, everything is done with the keyboard.
Python: Simple HTTP Server on python.
(Repost from old blog)
Python have several modules that help you to achieve your goals. This week, on my spare time that is getting every day more scarce I spend time figuring out how to create a Python Web Server, I was planing to use it over an application that I’m developing on ICT Consulting. At the end I didn’t use it because I didn’t want a “passive” communication, but probably I will use this code on the CRM Desktop application that we use here.
Anyway, this code may be helpful for you too. I found that creating a small web server is really simple, It starts getting bigger as you add functions to that web server, but the basis is quite simple.
import os
import cgi
import sys
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class customHTTPServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<HTML><body>Get!</body></HTML>')
return
def do_POST(self):
global rootnode
ctype,pdict = cgi.parse_header(self.headers.getheader('Content-type'))
if ctype == 'multipart/form-data':
query = cgi.parse_multipart(self.rfile, pdict)
self.send_response(301)
self.end_headers()
self.wfile.write('Post!')
def main():
try:
server = HTTPServer(('',8080),customHTTPServer)
print 'server started at port 8080'
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
if __name__=='__main__':
main()
Image as background in a Gtk Application.
(Reposted from the old blog)
This time I’m going to talk about putting an image as the application background in Gtk. In Gtk we are used to leave the colors of the application to the theme, but sometimes we will need to use an image as background. I already wrote how to draw a pixbuf in a gtk.DrawingArea (Esp), we could use that, but we will “draw” directly on the widget window instead.
Yes, I said the widget’s window instead the widget itself. You should know that every widget that has been packed in a container has a gtk.gdk.window object and is the responsible for containing your widget. Well, we can draw on that object.
What we need is to create a simple gtk.gdk.Pixbuf and call the gtk.gdk.window.draw_pixbuf method using your widget.window object on the expose-event.
The code should look like this:
#!/usr/bin/env python
import gtk
def draw_pixbuf(widget, event):
path = '/home/markuz/wallpapers/WMwall1024x768.gif'
pixbuf = gtk.gdk.pixbuf_new_from_file(path)
widget.window.draw_pixbuf(widget.style.bg_gc[gtk.STATE_NORMAL], pixbuf, 0, 0, 0,0)
window = gtk.Window()
window.set_title('Drawing Test')
window.set_size_request(640,480)
window.connect('destroy',gtk.main_quit)
hbbox = gtk.HButtonBox()
window.add(hbbox)
hbbox.connect('expose-event', draw_pixbuf)
button = gtk.Button('Press Me!')
hbbox.pack_start(button, True, False, 10)
window.show_all()
gtk.main()
Python trick: How to make lazy objects?
Reposting from the old blog.
Hay una versión de este post en español, si lo prefieres puedes léerla aquí: Truco de Python, como crear objetos “flojos” (Lazy objects)
This time I’m about to talk about lazy object, I called like that because they are more or less similar to what we use in lazy treeviews (In Gtk) where the Tree shows expanders but didn’t load the child nodes until you expand the node). What I want to do is create objects and count them, but don’t load any data until I need it.
Why would I need this?. Well. I’m currently writing a program for my employer, this program load a list of customers and shows how many accounts it has. As this accounts are kind of complex I create an object for them. This object is responsible for load/save the data for it, and any data you need is accessed via properties.
In my first approach, the object was loading the data as soon as the constructor was called, but sometimes I never access to any info in that object, remember, a customer may have many (and I mean really many) accounts, then why load all the data if there is a chance that I’ll never use it?. Well, that is because there is a chance that I have to use that data.
Then how could I create the object and then load the data when somebody require it?. That may be easy, may not. :-). One approach is making use of python properties. Just create the object and when someone want to use a “value” from the object use the property to retrieve the data, process it and then return a value. A simple property may be defined like this:
I just create a class “demo” and the property “some_property”, every time you use this:
Python will call the method get_some_property allowing you to do your trick. But if you have an object with more and more properties is better to get all data at one time and then just use properties to return a piece of it. You could call a method on every property if the data container is empty but for me it is not the best.
What you could do, is get the data the first time you need it. But, how could I know when a property/variable is requested on my object?
Well, Python classes have several reserved methods, and one of them is __getattribute__. This method let you handle every request to any property/class variable in your object.
With this you can dig in your object to know if the container is empty, and if it is empty fill it with data before returning the property value :-).
Lets say that the demo object have a __data dictionary containing the data. and propeties look into it for the right value, it also have a reference to the storage layer called storage.
Pay attention that I used object.__getattribute__ instead self.property, if I use self.property it will call self.__getattribute__ and will cause a recursion exception.
With this, we can create a great number of objects quickly and reducing the memory footprint. The downside is that getting the data will be a lot expensive if we require the data of all (or several) objects at once.
How would you do it?, let me know in the comments.
And it is there…
Kivy
The last couple of days I’ve been working with Kivy. For those that don’t know is a framework to create applications in graphical environments and in multiple platforms, all of these in the most easy to use programming language: Python, (And I mean programming language, JavaScript doesn’t count).
Well, its interesting to work with it, basically because I have the influence of GTK+ and having no windows but calling to widgets creates some confusion. Also, there is this Kivy language which is something like what Glade is In GTK but a lot easier to read (actually everything is easier to to read than XML).
I’m just starting to do this, this post is not a “how to do things in Kivy”, but I hope I can write some of those in the next weeks.