Wednesday, 23 August 2017

Bruno Rocha: Publish your Python packages easily using flit

Deploying Python Packages to PyPI using Flit

The traditional way of package deployment on Python is using a setup.py script located in the root of your project and then running python setup.py sdist upload to release a new version.

It works by using distutils, setuptools or distribute and there is also twine which is a command line application to manage uploads.

History

distutils is the standard way of Python package distribution included in standard library since Python 2.x then setuptools was created to overcome distutils limitations and also introduces a command line application called easy_install (which is now pip) and a very handy feature called pkg_resources and one of the characteristics of setuptools is that it uses Monkey Patching over the standard distutils.

Some forks of setuptools has been created to fix some issues and ad common developers preferences and well known forks like distribute and distutils2 and distlib has been merged back to the original setuptools

Lots of other packaging tools has been created to try to fix the distribution problems.

How it works in standard way

using one of the above you should create a file called setup.py in the root of your project, e.g:

from <my_favorite_dist_tool> import setup

# Example taken from Django's repository
setup(
    name='Django',
    version=version,
    url='http://ift.tt/q4NHeK',
    author='Django Software Foundation',
    author_email='foundation@djangoproject.com',
    description=('A high-level Python Web framework that encourages '
                 'rapid development and clean, pragmatic design.'),
    license='BSD',
    packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
    include_package_data=True,
    scripts=['django/bin/django-admin.py'],
    entry_points={'console_scripts': [
        'django-admin = django.core.management:execute_from_command_line',
    ]},
    install_requires=['pytz'],
    extras_require={
        "bcrypt": ["bcrypt"],
        "argon2": ["argon2-cffi >= 16.1.0"],
    },
    zip_safe=False,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP :: WSGI',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)

As you can see it is very confusing to decide which of them to addopt and how the setup.py should be writen because there are different examples over the github most famous Python repositories.

Making things easier with Flit

NOTE: Forget about all that history you read above and consider Flit.

Flit is a simple way to Package and deploy Python projects on PyPI, Flit makes it easier by using a simple flit.ini file and assumes common defaults to save your time and typing.

I knew Flit when I was taking a look at Mariatta Wijaya game called Tic Tac Taco Pizza and noted that she used flit to deploy the game, so we also asked her the reason on the podcast we recorded so I decided to try porting my projects to Flit.

How it works?

Instead of a setup.py you put a flit.ini in the root of your project and it looks like:

[metadata]
module = markdocs
author = Bruno Rocha
author-email = rochacbruno@gmail.com
maintainer = rochacbruno
maintainer-email = rochacbruno@gmail.com
home-page = http://ift.tt/2w1LXQ7
requires = mistune
           click
description-file = README.md
classifiers = Programming Language :: Python :: 3.6
              Intended Audience :: Developers
              License :: OSI Approved :: MIT License
              Topic :: Documentation
              Topic :: Software Development :: Documentation
              Topic :: Software Development :: Quality Assurance
requires-python = >=3.6

[scripts]
markdocs = markdocs:main

Now you only need to have flit installed in your local machine pip3 install flit as it works only in Python3+ and also is recommended to have pandoc and pypandoc also installed because it can convert your README.md into the .rst format still used by PyPI.

The advantages are:

  • No more complicated setup.py
  • If you omit some fields it will assume common used defaults
  • It is easier to read and write
  • Will convert your README.md
  • Will take the __version__ included in your program/__init__.py
  • Can develop to TestPyPI
  • Avoids over engineering on setup.py

Development installation

To install your package during development use

flit install --symlink --python path/to/virtualenv/bin/python

the --python is optional, by default will take the current which python

Registering and deploying

It is easy and will register the new project for you if doesn't exist on PyPI

flit puslish

Flit packages a single importable module or package at a time, using the import name as the name on PyPI. All subpackages and data files within a package are included automatically.

Important!

  • Flit will use the data from ~/.pypirc to authenticate and to find the server deployment addresses
  • You can also set FLIT_USERNAME and FLIT_PASSWORD and FLIT_INDEX_URL as environment variables which makes flit good for CI deployment (e.g: TravisCI)

What is missing?

NOTE: Flit is open-source, so some of this things are already under consideration.

  • Flit will not bump your project version automatically, you can still use tools like bumpversion but this feature would be better if builtin
  • Flit will not parse a requirements.txt file and would be nice to have it as tools like pyup.io can track those files but not flit.ini yet
  • Flit does not create a .lock frozen file with the version used on specific release and it is interesting just like pipenv does

Conclusion

Flit is the easier way to deploy packaged to PyPI following 3 steps (1. install flit, 2. describe flit.ini 3. run flit publish) your library is released to PyPI.

But Python still needs better standards because you still need separated tools to make common tasks and using a single tool to pack, install, deploy, create would be better (just like what cargo/crates does for Rust) for example, in Python you have:

  • Flit to deploy packages to PyPI for distribution
  • bumpversion to bump your semver number
  • pip to install and update packages from PyPI (or pipenv/WIP to do the same with more powers)
  • Cookiecutter to create a new Python Package (from strucured templates)
  • safety to check dependencies security
  • flake or pylint to static and styling checks
  • venv, pyenv or virtualenvwrapper to manage isolated environments
  • pytest to run tests
  • pyup to watch for depdendency updates

So many tools brings a lot of confusion and makes it hard to choose, why not having a single tool, based on different plugins sharing the same API?

Just an idea

python -m manage [install packagename]               # <-- calls pip or pipenv
                 [publish --options --bump=version]  # <-- calls `flit` and `bumpversion`
                 [new packagename templatename]      # <-- calls cookiecutter
                 [safecheck]                         # <-- calls safety
                 [checkupdates]                      # <-- checks in the same way as Pyup
                 [test path]                         # <-- calls pytest, nose or unittest
                 [lint path]                         # <-- calls flake, pylint 
                 [venv options]                      # <-- calls the existing venv module

All above configurable via config file or env vars.

and each of that endpoints would be provided by many plugins sharing the same API, so you could choose between flit or twine as your publish manager etc..

So maybe I can implement that features in manage

Please share in comments if you know some other Python management tool

What Does the Builtin Command in Bash Do?

The builtin commands in Bash can be extremely useful, but what does “builtin” itself actually do? Today’s SuperUser Q&A post has the answer to a curious reader’s question.

Weekly Python Chat: Q&A: __dunder__ variables in Python

Ever wondered what two underscores around variables means? You may have seen __name__, __str__, __doc__, or other "double underscore" variables in Python. What are these "dunder" variables and what are they for? This week we'll do a Q&A about dunder variables.

How to Enable Automatic Firmware Updates for Your Wink Hub

Firmware updates are annoying, but they’re essential to a properly working (and secure) device. The Wink Hub is no exception, but if you’d rather not have to deal with updating the hub every time new firmware comes out, you can actually enable automatic updates.

Geek Trivia: When You See New Growth Rising Out Of An Old Tree Stump, You’re Seeing A?

Think you know the answer? Click through to see if you're right!

Tuesday, 22 August 2017

How to Find You Wi-Fi Connected Roomba When It Gets Lost

If you leave your Roomba to do its thing unattended—which is the whole point, after all—every once in a while it can get stuck in a corner or under furniture. If you can’t figure out where it went, and you have a Wi-Fi connected model, you can ring it from the app to help you track it down.

Is Now a Good Time to Buy an Oculus Rift or HTC Vive?

The Oculus Rift and HTC Vive, the only retail-available VR headsets to use conventional gaming PCs as a platform, have been on the market for over a year. That’s long enough for fans to wonder when new models will be coming out…and long enough for sellers to want to move some of the existing stock. So, is it a good time to dive head-first into virtual reality?

How to Build Your Own NES or SNES Classic with a Raspberry Pi and RetroPie

The NES Classic Edition is an official clone of the original Nintendo Entertainment System, and one of the best ways to play your favorite retro games. The SNES Classic is its successor. Unfortunately, it’s so popular that it’s nearly impossible to get your hands on either. Don’t pay $300 on eBay when you can use the modestly-priced Raspberry Pi to build your own—with even more games.

The Best Tools for Editing Pictures on Chromebooks

Chromebooks have long been touted as great machines for users who “don’t need anything more than a browser.” But as time has gone on, the machines have gotten more powerful, with more program options are available than ever before. If you thought editing photos from a Chromebook wasn’t possible, it’s time to give it another look.

What Is a Macro Lens in Photography?

A macro lens is a lens designed for taking extremely close-up photos of the subject. If you’ve ever seen a photo of a spider’s eyes or the veins of a leaf, that was a macro photo.

Talk Python to Me: #126 Kubernetes for Pythonistas

Containers are revolutionizing the way we deploy and manage applications. These containers allow us to build, develop, test, and even deploy on the exact same system. We can build layered systems that fill in our dependencies. They even can play a crucial role in zero-downtime upgrades.

This is great, until you end up with 5 different types of containers, each of them scaled out, and you need to get them to work together, discover each other and upgrade together. That's where Kubernetes comes it.

Today you'll meet Kelsey Hightower, a developer advocate on Google's cloud platform.

Gocept Weblog: Zope preparing to enter Python 3 wonderland

Once upon the time there was an earl named Zope II. His prophets told him that around the year 2020 suddenly his peaceful country will be devastated: They proclaim that with the “sunset” of  Python 2 as stable pillar of his country, insecurity and pain will invade his borders and hurt everyone living within. There seemed only one possible move forward to escape the disaster: Flee to the Python 3 wonderland, the source of peace and prosperity.

This was not as easy as one might think. Earl Zope II was already an old man. He was in the stable age where changes are no longer easy to achieve and he had many courtiers in his staff which he needed all the day.

The immigration authority of the Python 3 wonderland was very picky about the persons which requested permission to settle down. Many “updates” for Zope II and his staff where required to so they eventually became “compatible” with the new country. Earl Zope II was even forced to change his name to Zope IV to show hat he was ready for Python 3 wonderland.

After much work with the immigration authorities it seemed to be possible for earl Zope IV to enter; only some – but important – formalities were needed before he could be allowed to settle down and call himself a citizen of the Python 3 wonderland.

This is where the tale gets real: We need your help to release a beta version of Zope 4. The hard work seems to be done; but some polish and testing is still required to reach this goal.

We invite you to the Zope 4 Phoenix Sprint to help raising Zope 4 from the ashes! From Wednesday, 13th until Friday, 15th of September 2017 we sprint at the gocept office in Halle (Saale), Germany towards the beta release.

Possible sprint topics could be:

  • Work on issues and pull requests regarding the beta release.
  • Make RestrictedPython beta ready.
  • Work on a Bootstrap of the Zope management interface (ZMI)
  • Port CMF components to Python 3 to test Zope 4 for possible issues
  • Work on Plone to make it ready for Zope 4
  • Try out migration strategies for ZODB content to Python 3.
  • Improve the documentation.

You are heartily invited to join us for the honour of earl Zope IV.


Daniel Bader: What Are Python Generators?

What Are Python Generators?

Generators are a tricky subject in Python. With this tutorial you’ll make the leap from class-based iterators to using generator functions and the “yield” statement in no time.
If you’ve ever implemented a class-based iterator from scratch in Python, you know that this endeavour requires writing quite a bit of boilerplate code.
And yet, iterators are so useful in Python: They allow you to write pretty for-in loops and help you make your code more Pythonic and efficient.
As a (proud) “lazy” Python developer, I don’t like tedious and repetitive work. And so, I often found myself wondering:
If there only was a more convenient way to write these Python iterators in the first place…
Surprise, there is! Once again, Python helps us out with some syntactic sugar to make writing iterators easier.
In this tutorial you’ll see how to write Python iterators faster and with less code using generators and the yield keyword.
Ready? Let’s go!

Python Generators 101 – The Basics

Let’s start by looking again at the Repeater example that I previously used to introduce the idea of iterators. It implemented a class-based iterator cycling through an infinite sequence of values.
This is what the class looked like in its second (simplified) version:
class Repeater:
    def __init__(self, value):
        self.value = value

    def __iter__(self):
        return self

    def __next__(self):
        return self.value
If you’re thinking, “that’s quite a lot of code for such a simple iterator,” you’re absolutely right. Parts of this class seem rather formulaic, as if they would be written in exactly the same way from one class-based iterator to the next.
This is where Python’s generators enter the scene. If I rewrite this iterator class as a generator, it looks like this:
def repeater(value):
    while True:
        yield value
We just went from seven lines of code to three.
Not bad, eh? As you can see, generators look like regular functions but instead of using the return statement, they use yield to pass data back to the caller.
Will this new generator implementation still work the same way as our class-based iterator did? Let’s bust out the for-in loop test to find out:
>>> for x in repeater('Hi'):
...    print(x)
'Hi'
'Hi'
'Hi'
'Hi'
'Hi'
...
Yep! We’re still looping through our greetings forever. This much shorter generator implementation seems to perform the same way that the Repeater class did.
(Remember to hit Ctrl+C if you want out of the infinite loop in an interpreter session.)
Now, how do these generators work? They look like normal functions, but their behavior is quite different. For starters, calling a generator function doesn’t even run the function. It merely creates and returns a generator object:
>>> repeater('Hey')
<generator object repeater at 0x107bcdbf8>
The code in the generator function only executes when next() is called on the generator object:
>>> generator_obj = repeater('Hey')
>>> next(generator_obj)
'Hey'
If you read the code of the repeater function again, it looks like the yield keyword in there somehow stops this generator function in mid-execution and then resumes it at a later point in time:
def repeater(value):
    while True:
        yield value
And that’s quite a fitting mental model for what happens here. You see, when a return statement is invoked inside a function, it permanently passes control back to the caller of the function. When a yield is invoked, it also passes control back to the caller of the function—but it only does so temporarily.
Whereas a return statement disposes of a function’s local state, a yield statement suspends the function and retains its local state.
In practical terms, this means local variables and the execution state of the generator function are only stashed away temporarily and not thrown out completely.
Execution can be resumed at any time by calling next() on the generator:
>>> iterator = repeater('Hi')
>>> next(iterator)
'Hi'
>>> next(iterator)
'Hi'
>>> next(iterator)
'Hi'
This makes generators fully compatible with the iterator protocol. For this reason, I like to think of them primarily as syntactic sugar for implementing iterators.
You’ll find that for most types of iterators, writing a generator function will be easier and more readable than defining a long-winded class-based iterator.

Python Generators That Stop Generating

In this tutorial we started out by writing an infinite generator once again. By now you’re probably wondering how to write a generator that stops producing values after a while, instead of going on and on forever.
Remember, in our class-based iterator we were able to signal the end of iteration by manually raising a StopIteration exception. Because generators are fully compatible with class-based iterators, that’s still what happens behind the scenes.
Thankfully, as programmers we get to work with a nicer interface this time around. Generators stop generating values as soon as control flow returns from the generator function by any means other than a yield statement. This means you no longer have to worry about raising StopIteration at all!
Here’s an example:
def repeat_three_times(value):
    yield value
    yield value
    yield value
Notice how this generator function doesn’t include any kind of loop. In fact it’s dead simple and only consists of three yield statements. If a yield temporarily suspends execution of the function and passes back a value to the caller, what will happen when we reach the end of this generator?
Let’s find out:
>>> for x in repeat_three_times('Hey there'):
...     print(x)
'Hey there'
'Hey there'
'Hey there'
As you may have expected, this generator stopped producing new values after three iterations. We can assume that it did so by raising a StopIteration exception when execution reached the end of the function.
But to be sure, let’s confirm that with another experiment:
>>> iterator = repeat_three_times('Hey there')
>>> next(iterator)
'Hey there'
>>> next(iterator)
'Hey there'
>>> next(iterator)
'Hey there'
>>> next(iterator)
StopIteration
>>> next(iterator)
StopIteration
This iterator behaved just like we expected. As soon as we reach the end of the generator function, it keeps raising StopIteration to signal that it has no more values to provide.
Let’s come back to another example from my Python iterators tutorials. The BoundedIterator class implemented an iterator that would only repeat a value a set number of times:
class BoundedRepeater:
    def __init__(self, value, max_repeats):
        self.value = value
        self.max_repeats = max_repeats
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.max_repeats:
            raise StopIteration
        self.count += 1
        return self.value
Why don’t we try to re-implement this BoundedRepeater class as a generator function. Here’s my first take on it:
def bounded_repeater(value, max_repeats):
    count = 0
    while True:
        if count >= max_repeats:
            return
        count += 1
        yield value
I intentionally made the while loop in this function a little unwieldy. I wanted to demonstrate how invoking a return statement from a generator causes iteration to stop with a StopIteration exception. We’ll soon clean up and simplify this generator function some more, but first let’s try out what we’ve got so far:
>>> for x in bounded_repeater('Hi', 4):
...     print(x)
'Hi'
'Hi'
'Hi'
'Hi'
Great! Now we have a generator that stops producing values after a configurable number of repetitions. It uses the yield statement to pass back values until it finally hits the return statement and iteration stops.
Like I promised you, we can further simplify this generator. We’ll take advantage of the fact that Python adds an implicit return None statement to the end of every function. This is what our final implementation looks like:
def bounded_repeater(value, max_repeats):
    for i in range(max_repeats):
        yield value
Feel free to confirm that this simplified generator still works the same way. All things considered, we went from a 12-line iterator in the BoundedRepeater class to a three-line generator-based implementation providing the same functionality.
That’s a 75% reduction in the number of lines of code—not too shabby!
Generator functions are a great feature in Python, and you shouldn’t hesitate to use them in your own programs.
As you just saw, generators help you “abstract away” most of the boilerplate code otherwise needed when writing class-based iterators. Generators can make your life as a Pythonista much easier and allow you to write cleaner, shorter, and more maintainable iterators.

Python Generators – A Quick Summary

  • Generator functions are syntactic sugar for writing objects that support the iterator protocol. Generators abstract away much of the boilerplate code needed when writing class-based iterators.
  • The yield statement allows you to temporarily suspend execution of a generator function and to pass back values from it.
  • Generators start raising StopIteration exceptions after control flow leaves the generator function by any means other than a yield statement.

Announcing Open Jam, a game jam created with open source in mind

Announcing Open Jam

After more than a year of participating in game jams as Team Scripta, we wanted to host one that promotes open source games and game creation tools. That's why we're teaming up with Opensource.com to bring you Open Jam, a game jam dedicated to doing just that.


read more

Astroplan Python library makes astronomy research planning easier

Astroplan makes astronomy research planning easier

For some people, the darkness of the recent eclipse set off a light bulb. As millions of people saw the sun blotted out by the moon, many of them realized they're interested in astronomy more generally. Those people are in luck. A Python library called Astroplan can help them plan their observations.


read more

4 open principles for building a better startup

4 open principles for building a better startup

If you're launching a company, you might believe you shouldn't have to deal with issues like personnel development and company culture. After all, as a startup you're only concerned with the development and rapid evolution of your own product and services, right?

This kind of thinking is short-term thinking. Successful startups develop organizations with long-term strategies in mind. Startups really should think about—and prepare the groundwork for—their own company culture from beginning, so they can scale it over time as they grow.


read more

How many of your games run on Linux?

How many of your games run on Linux?

Gamer? Check. Linux user? Check.

For years, one of the top excuses I heard from friends who would otherwise have switched to Linux long ago is that they just couldn't give up their Windows-only games. I can empathize. I was a dual-booter for years for exactly this reason, and it made making the switch harder for me. After all, once I'm booted into one operating system, the temptation is to stay there rather than rebooting once gameplay is over.

Today, the landscape is far different. It's much easier than it used to be for a gamer to be a Linux user, and vice versa.


read more

The Best New Features in Android 8.0 Oreo, Available Now

Android “O” is officially Android Oreo, which is beginning to roll out to compatible devices now. As with most major Android releases, this one brings a host of new features and improvements over its predecessor, Android Nougat. Here’s a glimpse of what to expect when Oreo lands on your device.

How to Skip the Wait and Upgrade Your Pixel or Nexus to Android Oreo Now

Android Oreo is here, but it’s rolling out to Pixel and Nexus devices slowly. If you still haven’t gotten the upgrade notification, here’s a little trick to upgrade sooner.

How to Randomize Your Hue Lights for Extra Vacation Security

If you want to give the illusion that you’re home when you’re really on vacation, your Phillips Hue smart bulbs now have a “presence mimicking” feature that makes crafting the illusion dead simple.

Are Smart Locks Secure?

You might think that smart locks are a security disaster just waiting to happen. After all, why would you trust an internet-connected device with the security of your house and everything in it? But consider this: locks are pretty insecure are in general.

Geek Trivia: The First Companion Character Link Has In Any Of The Legend Of Zelda Games Is?

Think you know the answer? Click through to see if you're right!

Monday, 21 August 2017

How to Middle Click on a Laptop Touchpad

Most laptop touchpads make it possible to perform a middle-click, but not all do. In some situations, you may need to enable this option in your mouse driver’s control panel or install the appropriate drivers first.

How to Make Phone Calls With Your Google Home

After Alexa gave users the ability to call other Echo owners, Google upped the ante with true phone calls. If you live in the U.S. or Canada, you can now use your Google Home to place a call to anyone’s phone. You don’t need to limit yourself to other people who have a Google Home. Here’s how to get started making phone calls.

What Is “SmartScreen” and Why Is It Running on My PC?

Windows 10 includes SmartScreen, a feature that helps protect your PC from downloaded malware and malicious websites. The “SmartScreen” process—with the filename “smartscreen.exe”—that you see in Task Manager is responsible for this feature.

How to Customize Your Command Prompt’s Color Scheme With Microsoft’s ColorTool

Microsoft created a new console color scheme for Windows 10’s Fall Creators Update, but existing Windows systems won’t get it automatically. A new, official tool allows you to install this new color scheme and other ones for easy customization of your Command Prompt windows.

How to Leave a Facebook Group

One of Facebook’s most annoying features is that any of your Friends can add you to a Facebook Group. I’ve had several acquaintances who are selling Herbalife or similar things add me to Groups promoting their dubious products. If the same thing happens to you or you just want to leave a Facebook Group because it’s no longer relevant to you, here’s how.

Why You Should Replace Windows’ Default Image Viewer With IrfanView

As its featureset expanded, Windows became something of an omnibus. It now includes not one, but two built-in browsers, a defragmentation tool, and even Candy Crush. But like most do-it-all tools, just because Windows can do almost everything doesn’t mean it’s the best way to do anything. So it is with the default photo viewer.

Geek Trivia: The Smallest Fox Species In The World Is The?

Think you know the answer? Click through to see if you're right!

Thursday, 25 July 2013

Installing SSH2 Extension for PHP on CentOS 5

Download the rpmforge-release package

http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm

rpm -i rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm


yum install gcc php-devel php-pear libssh2 libssh2-devel


pecl install -f ssh2
touch /etc/php.d/ssh2.ini

echo extension=ssh2.so > /etc/php.d/ssh2.ini

/etc/init.d/httpd restart 

php -m | grep ssh2