Sunday, February 28, 2021

Matthew Wright: Profiling Python code with line_profiler

Once we have debugged, working, readable (and hopefully testable) code, it may become important to examine it more closely and try to improve the code's performance. Before we can make any progress in determining if our changes are an improvement, we need to measure the current performance and see where it is spending its time. … Continue reading Profiling Python code with line_profiler

The post Profiling Python code with line_profiler appeared first on wrighters.io.



from Planet Python
via read more

Test and Code: 146: Automation Tools for Web App and API Development and Maintenance - Michael Kennedy

Building any software, including web apps and APIs requires testing.
There's automated testing, and there's manual testing.

In between that is exploratory testing aided by automation tools.

Michael Kennedy joins the show this week to share some of the tools he uses during development and maintenance.

We talk about tools used for semi-automated exploratory testing.
We also talk about some of the other tools and techniques he uses to keep Talk Python Training, Talk Python, and Python Bytes all up and running smoothly.

We talk about:

  • Postman
  • ngrok
  • sitemap link testing
  • scripts for manual processes
  • using failover servers during maintenance, redeployments, etc
  • gitHub webhooks and scripts to between fail over servers and production during deployments automatically
  • floating IP addresses
  • services to monitor your site: StatusCake, BetterUptime
  • the affect of monitoring on analytics
  • crash reporting: Rollbar, Sentry
  • response times
  • load testing: Locus

Special Guest: Michael Kennedy.

Sponsored By:

Support Test & Code : Python Testing

Links:

<p>Building any software, including web apps and APIs requires testing.<br> There&#39;s automated testing, and there&#39;s manual testing.<br><br> In between that is exploratory testing aided by automation tools. </p> <p>Michael Kennedy joins the show this week to share some of the tools he uses during development and maintenance.</p> <p>We talk about tools used for semi-automated exploratory testing. <br> We also talk about some of the other tools and techniques he uses to keep Talk Python Training, Talk Python, and Python Bytes all up and running smoothly. </p> <p>We talk about:</p> <ul> <li>Postman</li> <li>ngrok</li> <li>sitemap link testing</li> <li>scripts for manual processes</li> <li>using failover servers during maintenance, redeployments, etc</li> <li>gitHub webhooks and scripts to between fail over servers and production during deployments automatically</li> <li>floating IP addresses </li> <li>services to monitor your site: StatusCake, BetterUptime</li> <li>the affect of monitoring on analytics</li> <li>crash reporting: Rollbar, Sentry</li> <li>response times</li> <li>load testing: Locus</li> </ul><p>Special Guest: Michael Kennedy.</p><p>Sponsored By:</p><ul><li><a href="https://ift.tt/3rMDLio" rel="nofollow">Linode</a>: <a href="https://ift.tt/3rMDLio" rel="nofollow">If it runs on Linux, it runs on Linode. Get started on Linode today with $100 in free credit for listeners of Test & Code.</a></li></ul><p><a href="https://ift.tt/2tzXV5e" rel="payment">Support Test & Code : Python Testing</a></p><p>Links:</p><ul><li><a href="https://pythonbytes.fm/" title="Python Bytes Podcast" rel="nofollow">Python Bytes Podcast</a></li><li><a href="https://talkpython.fm/" title="Talk Python To Me Podcast" rel="nofollow">Talk Python To Me Podcast</a></li><li><a href="https://ift.tt/1UwVvdh" title="Talk Python Training" rel="nofollow">Talk Python Training</a></li><li><a href="https://ift.tt/32MbnS3" title="Postman" rel="nofollow">Postman</a></li><li><a href="https://ngrok.com/" title="ngrok" rel="nofollow">ngrok</a></li><li><a href="https://ift.tt/TjZ7Ct" title="StatusCake" rel="nofollow">StatusCake</a></li><li><a href="https://ift.tt/2LmuGd1" title="Better Uptime" rel="nofollow">Better Uptime</a></li><li><a href="https://ift.tt/3sGh6EZ" title="Rollbar" rel="nofollow">Rollbar</a></li><li><a href="https://sentry.io" title="Sentry" rel="nofollow">Sentry</a></li><li><a href="https://locust.io/" title="Locust" rel="nofollow">Locust</a></li><li><a href="https://ift.tt/39g3JEt" title="12 requests per second in Python" rel="nofollow">12 requests per second in Python</a></li></ul>

from Planet Python
via read more

Codementor: Server deployment with Python: From A to Z.

In this tutorial you will learn how to configure a server and deploy a web app from scratch by using only Python.

from Planet Python
via read more

Saturday, February 27, 2021

The Open Sourcerer: A new data format has landed in the upcoming GTG 0.5

Here’s a general call for testing from your favorite pythonic native Linux desktop personal productivity app, GTG.

In recent months, Diego tackled the epic task of redesigning the XML file format from a new specification devised with the help of Brent Saner (proposal episodes 1, 2 and 3), and then implementing the new file format in GTG. This work has now been merged to the main development branch on GTG’s git repository:

Diego’s changes are major, invasive technological changes, and they would benefit from extensive testing by everybody with “real data” before 0.5 happens (very soon). I’ve done some pretty extensive testing & bug reporting in the last few months; Diego fixed all the issues I’ve reported so far, so I’ve pretty much run out of serious bugs now, as only a few remain targetted to the 0.5 milestone… But I’m only human, and it is possible that issues might remain, even after my troll-testing.

Grab GTG’s git version ASAP, with a copy of your real data (for extra caution, and also because we want you to test with real data); see the instructions in the README, including the “Where is my user data and config stored?” section.

Please torture-test it to make sure everything is working properly, and report issues you may find (if any). Look for anything that might seem broken “compared to 0.4”, incorrect task parenting/associations, incorrect tagging, broken content, etc.

If you’ve tried to break it and still couldn’t find any problems, maybe one way to indicate that would be a “👍” on the merge request—I’m not sure we really have another way to know if it turns out that “everything is OK” 🙂

Your help in testing this (or spreading the word) will help ensure a smooth transition for users getting an upgrade from 0.4 to 0.5, letting us release 0.5 with confidence. Thanks!



from Planet Python
via read more

Weekly Python StackOverflow Report: (cclxv) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2021-02-27 18:35:08 GMT


  1. Why aren't my list elements being swapped? - [11/1]
  2. Title words in a column except certain words - [8/4]
  3. specify number of spaces between pandas DataFrame columns when printing - [8/1]
  4. More effective / clean way to aggregate data - [5/5]
  5. Is there a way to write this if-else using min and max? - [5/4]
  6. What does the operator += return in Python - [5/4]
  7. Find missing numbers in a sorted column in Pandas Dataframe - [5/3]
  8. Perform best cycle sort knowing order at the end - [5/1]
  9. Making a scroll bar but its inconsistent - [5/1]
  10. Python import mechanism and module mocks - [5/1]


from Planet Python
via read more

Corey Gallon: 3 Simple Steps to Build a Python Package for Conda Forge

In just 3 easy steps, we’ll package the spotipy Python library for Conda Forge!

Hey data hackers! We’re all raving fans of Conda Forge — the community-led repository of recipes, build infrastructure and distributions for the conda package manager, right? It’s a rich source of the most useful, updated libraries for Python (and many other languages, including R, Ruby, Lua, Scala, Java, JavaScript, C/ C++, FORTRAN … the list goes on). You may well have found, though, that the library you’re looking for isn’t available in the repo, which is precisely what I found recently when building a machine learning model to predict song popularity, based on its musical attributes. What does one do in such a situation? Package the library yourself, of course! While this may seem a daunting task, we’ll work through 3 simple steps to building a Python package for Conda Forge, and submitting it to the repository.

Why build a package for Conda Forge?

The excellent spotipy library, written and maintained by the similarly awesome data scientist and developer Paul Lamere (Director of the Developer Platform at Spotify), is (well … was) not available in Conda Forge. This library is a Python wrapper for the Spotify API. Recently, I wrote a machine learning model to predict a song’s popularity based on its musical attributes. The data underlying the model were to be pulled from the Spotify API, using the spotipy library. Unfortunately, at the time I went to build the model, the only Python package repo offering spotipy was PyPI (the repo that ‘pip’ installs from). You, like me, may have learned the hard way that it is unadvised to mix packages from both pip and conda in a conda environment. In order to get through my little machine learning project, I downloaded the spotipy source code from PyPI and both built and installed it locally. Wanting to write about the project, though, I realized that this approach is suboptimal for most who want to hackalong with the article, hence the decision to package spotipy myself.

“Enough background, already — let’s build!”

Rightho! Enough background … let’s get started! The good people at Conda Forge provide detailed instructions on how to contribute packages to the repo. We’ll distill, from these detailed instructions, 3 simple steps to follow to build and contribute your Python package to Conda Forge.

  1. Fork the Conda Forge examples recipes repository at GitHub
  2. Tailor the example recipe for your package
  3. Submit a pull request to Conda Forge

Let’s get into it!

1. Fork the Conda Forge examples repository at GitHub

Before we head over to GitHub, be sure that the source code for your package is available for download in a single file. This should be an archive (e.g. tarball, zip, etc …) of some kind. In this case, as we’re packaging spotipy from PyPI, we can confirm that the source code is, indeed, available in a gzipped tarball there. You should confirm, similarly, for the package you plan to build and contribute.

We’ll be working in GitHub for this project. If you’ve never used GitHub before, or need a brief refresher, here’s the great Hello World! documentation they offer.

Okay! Pop over to GitHub and open the ‘staged-recipes’ repository in GitHub Desktop. This will clone the repo to your local machine.

Clone the repo locally by opening it in GitHub Desktop

In GitHub Desktop, within your newly forked repo, create a new branch from the staged-recipes master branch. Name the new branch as is sensible for your package. In this case, I named the branch ‘spotipy’. To create a new branch, simply click the ‘master’ branch button and type the name of the new branch into the ‘Filter’ text field.

Create a new branch by typing the name of the branch and hitting the ‘New branch’ button

Now we’ll create a new folder in the ‘recipes’ folder, and copy the example recipe into the new folder. To do this, open the files in the repository in your operating system’s file browser.

Open the files of the repo within your operating system’s file browser

The newly opened window will look something like this, depending on your operating system (this is Windows 10)

These are the files of the cloned repository

Navigate to the ‘recipes’ folder (highlighted above) and create a copy of the ‘example’ folder (CTRL + drag the folder in Windows 10), then rename it to reflect your package name. NB this is an important step — don’t just create a folder, copy and rename it so that the example ‘meta.yaml’ file is copied also.

Copy and rename the ‘example’ folder to your package name

Within your newly created folder, open the meta.yaml file in your favorite text editor, and …

2. Tailor the example recipe for your package

Conda Forge recipes are written in the YAML (YAML Ain’t Markup Language) data serialization language. If you’ve not written YAML before, or need a brief refresher, here’s a great reference. The copy of the example recipe meta.yaml file looks like this

Again, the good people at Conda Forge provide very detailed instructions on how to edit this file — both in the file itself, and in their documentation. Another vital bit of documentation is provided by conda here. Let’s save you the hassle of reading through all of this at the start, though I found myself referencing these docs frequently throughout the process and strongly suggest you come back and do the same.

Pro tip: use the Python ‘grayskull’ package to automatically create a near-perfect meta.yaml file!

I spent ages the first time I did this manually editing the meta.yaml file for my package and iteratively submitting it via a pull request. It turns out that all of that brain damage can be avoided by using the Python packaging tools provided by conda to generate this file. The documentation provided by the Conda team is helpful, though the approach outlined here (i.e. using conda skeleton) did not work for me because, I learned after much banging of my head against the keyboard, conda skeleton needs a major refactoring.

Enter grayskull, which will eventually replace conda skeleton. Grayskull is a tool to generate concise recipes for Conda Forge — precisely the task at hand! We won’t go through the process of creating a new conda environment here. Simply install grayskull from conda forge in a new conda environment as follows:

conda install -c conda-forge grayskull

With grayskull installed, use it to build a meta.yaml (recipe) for your package, by calling it, passing it the repository in which the package presently lives, and the name of the package. In our case:

grayskull pypi spotipy

Upon a successful build, you’ll see something like this …

grayskull has successfully built a recipe for the spotipy package

… and there will be a newly created folder with the name of your package. Inside this folder, you’ll find a near-perfect recipe to inform your tailoring of the meta.yaml file you’ve copied in your local clone of the repo above.

At this point, you could either copy and paste the file into your clone of the repo, overwriting the example file above, or edit the example file down using this information as inputs. I suggest the latter, as the recipe that grayskull creates isn’t quite perfect and will likely be rejected during the pull request process without some edits. Importantly, in this case, Conda Forge requires minimum version limits for Python because we’re building to the ‘noarch’ (i.e. operating system non-specific) target. The edits are simple enough, though. In the ‘requirements’ section of the YAML file, add minimum versions to the python lines for both host and run.

… annnnnnnd we’re donezo! The final, pull request-ready recipe meta.yaml file for the spotipy package is as follows.

Note the subtle differences between this file and the one generated by grayskull. Again, I recommend editing the file using the output of grayskull rather than copying and pasting to avoid potential issues during the pull request process.

3. Submit a pull request to Conda Forge

Rightho! We’re almost finished. All that remains is to submit a pull request to the maintainers of Conda Forge. Before we do, we’ll need to commit the changes we’ve made in our local clone of the GitHub.

Commit the changes to the local repository

Now we’ll push the commit back to GitHub.

Push the local commit back to GitHub

Excellent! Now it’s time to submit our pull request.

They have a really dope continuous integration (CI) pipeline that automates most of the pull request process! A reviewer from the Conda Forge team will, ultimately, review and approve the request, but there is a heap of great feedback from their automated CI that really speeds the process up.

Important note: do not fully submit a pull request for the spotipy package if you’ve been hacking-along with this article, as it will be rejected as a duplicate (of the package I’ve already contributed).

When we select “Pull request” from the GitHub desktop app, we’re returned to the GitHub website to complete the process. Click the ‘Pull request’ link at the top right of the repo.

Initiate a pull request to the Conda Forge repo

The next screen shows you compared changes between the original repo we cloned, and the edits we’ve made.

We can see the changes that were made via commits to the repo

Click the green “Create pull request” button. In the next screen, provide an informative title for the pull request and work carefully through each item of the checklist to confirm that all of the requirements are met.

Provide an informative title for the pull request
Be sure to work through each of the checklist requirements and confirm they are satisfied

Once the pull request is submitted, the aforementioned slick CI process is kicked off and works through 5 automated steps. These include linting, checking the package builds, then checking that the package builds for each of 3 target operating systems (Linux, OSX and Windows). When these checks successfully complete, you’ll be notified. (This process can take as much as half an hour or so … be patient!)

Brilliant! We’ve passed all 5 of the checks that the CI process ran automatically.

Now … we play the waiting game until we hear back from the maintainers with any additional feedback …

In a little while (a few hours, in this case) the maintainers will respond with either feedback or, if all went well, confirmation that the pull request was merged. Congratulations — you are now a package maintainer for Conda Forge! You’ll receive an email invitation to the Conda Forge organization on GitHub, which must be accepted within 7 days. After accepting, the automated CI process will build the package so that it is available at Conda Forge. Here’s the spotipy package.

Love it! Here’s the spotipy package now incorporated in the Conda Forge repo!

We can also run a quick search from the shell to confirm that the package is available to install via conda

conda search -c conda-forge spotipy
spotipy is ready to install via conda!

… and that’s it! I hope you’ve found this both interesting and accelerating as you make your way into the wonderful world of Python packaging for Conda Forge!

What the huh!? Problems I encountered along the way …

This article comes together in a way that suggests graceful ease of development. As usual, that was certainly not the case. Here are a few things I learned by banging my head against the keyboard during the process of packaging spotipy for Conda Forge.

  • grayskull would have saved me heaps of time that was otherwise spent digging through source code trying to figure out how to edit the meta.yaml file for the package recipe. In addition to digging through the source code, I spent entirely too much time trying to parse the PKG-INFO file it contains into a recipe for Conda Forge. It worked, and I managed to get it packaged, but OMG grayskull FTW! This article would have been a much longer, more tedious piece without this learning.
  • The documentation provided by the Conda team on packaging for Conda is outdated and doesn’t work. My first foray into packaging was a frustrating failure as a result, leaving hours spent without the outcome I expected (though I learned a lot). I even ended up posting to the anaconda.org mailing list looking for help, which never came. Perhaps one day, if I muster the motivation, I’ll edit the docs and submit a pull request to update the broken bits.
  • As always, reading the documentation is particularly helpful. Despite the hackalong provided in this article, I strongly recommend reading the docs I’ve linked to in order to better understand the packaging process.

Screencast forthcoming!

Stay tuned for a video walkthrough of this article!



from Planet Python
via read more

Andre Roberge: Friendly-traceback: testing with Real Python

Real Python is an excellent learning resource for beginning and intermediate Python programmers that want to learn more about various Python related topics. Most of the resources of RealPython are behind a paywall, but there are many articles available for free. One of the free articles, Invalid Syntax in Python: Common Reasons for SyntaxError, is a good overview of possible causes of syntax errors when using Python. The Real Python article shows code raising exceptions due to syntax errors and provides some explanation for each case.

In this blog post, I reproduce the cases covered in the Real Python article and show the information provided by Friendly-traceback. Ideally, you should read this blog post side by side with the Real Python article, as I mostly focus on showing screen captures, with very little added explanation or background.

If you want to follow along using Friendly-traceback, make sure that you use version 0.2.34 or newer.

Missing comma: first example from the article

The article starts off showing some code leading to this rather terse and uninformative traceback.


Since the code is found in a file, we use python -m friendly_traceback theofficefacts.py to run it and obtain the following.


Misusing the Assignment Operator (=)

We only show one example here, as the others mentioned in the article would be redundant. We remind you for one last time that, if you are not doing so, you should really look at the Real Python article at the same time as you go through this rather terse blog post.


Friendly traceback provides a "hint" right after the traceback. We can get more information by asking why().


Misspelling, Missing, or Misusing Python Keywords

Identifying misspelled keywords was actually inspired by that article from Real Python.



Note that Friendly-traceback identifies "for" as being the most likely misspelled keyword, but gives other possible valid choices.

Friendly-traceback can also identify when break (and return) are used outside a loop.



To the English reader, Friendly-traceback might seem to add very little useful information. However, keep in mind that all this additional information can be translated. If you read the following and do not understand what "boucle" means, then you might get an idea of the some of the challenges faced by non-English speakers when using Python.


In some other cases, like the example given in the Real Python article, Friendly-traceback can identify a missing keyword.


As long as there is only one instance of "in" missing, Friendly-traceback can identify it properly.


Finally, two more cases where a Python keyword is not used properly.



Missing Parentheses, Brackets, and Quotes

Five examples taken from the Real Python article offered without additional comments.






Mistaking Dictionary Syntax


Using the Wrong Indentation

Real Python gives many examples. They would all be handled correctly by Friendly-traceback in a similar way as the single example we decided to use for this post.



Defining and Calling Functions




Changing Python Versions



Friendly-traceback requires Python version 3.6 or newer. Not shown here is that it can recognize that the walrus operator, :=, is not valid before Python version 3.8 and give an appropriate message.


Last example: TypeError result of a syntax error.

Let's look at the last example in the Real Python article.


The explanation given by Friendly-traceback might seem weird "the object (1, 2) was meant to be a function ...".  Often one might have assigned a name to that object, which leads to an explanation that should be seen as more reasonable.




The explanation of looking for a "missing comma" when this TypeError is raised was actually added following a suggestion by S. de Menten in the recent contest I held for Friendly-traceback.

There is more ...

Friendly-traceback includes many more cases that those shown above and mentioned in the Real Python article. However, it is limited in that it can only identify the cause of syntax errors there is a single word or symbol used incorrectly or if the error message provided by Python is more informative than the dreaded SyntaxError: invalid syntax.


from Planet Python
via read more

Fabio Zadrozny: PyDev 8.2.0 released (external linters, Flake8, path mappings, ...)

 PyDev 8.2.0 is now available for download.

This release has many improvements for dealing with external linters.

The main ones are the inclusion of support for the Flake8 linter as well as using a single linter call for analyzing a directory, so, that should be much faster now (previously it called external linters once for each file) .

Note: to request code analysis for all the contents below a folder, right-click it and choose PyDev > Code analysis:

Another change is that comments are now added to the line indentation... 

This means that some code as:

  def method():  
if True:
pass

Will become:

  def method():  
# if True:
# pass

p.s.: it's possible to revert to the old behavior by changing the preferences at PyDev > Editor > Code Style > Comments. 

Also note that after some feedback, on the next release an option to format such as the code below will also be added (and will probably be made the default):

  def method():  
# if True:
# pass

Interpreter configuration also got a revamp:

So, it's possible to set a given interpreter to be the default one and if you work with conda, select Choose from Conda to select one of your conda environments and configure it in PyDev.

Path mappings for remote debugging can now (finally) be configured from within PyDev itself, so, changing environment variables is no longer needed for that:

 

Note that Add path mappings template entry may be clicked multiple times to add multiple entries.

That's it... More details may be found at: http://pydev.org.

Hope you enjoy the release 😊




from Planet Python
via read more

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...