Quantcast
Channel: Planet Python
Viewing all 22872 articles
Browse latest View live

Continuum Analytics Blog: Moving Conda Environments

$
0
0

Conda is known as a package manager for Python and R packages produced by Anaconda, Inc. and conda-forge, the open-source community for conda Python packages. In addition to managing packages, Conda is also an environment…

The post Moving Conda Environments appeared first on Anaconda.


PSF GSoC students blogs: Week 12: Blog Post (#6)

$
0
0

Last week, I worked on several steps to finalize my project.
Some work was put into correcting and improving my pull requests, so they can be merged soon. I created an example file to demonstrate the useability of this project, and opened up a new pull request for it (next to another PR, that introduces the plotting support I implemented the previous week).
As mentioned in my last blog post, I also thought about an alternative solution, i.e. to create a genuine plotting function for SourceTFR. But as I already suspected, this will not work without a lot of additional work. I originally intended to introduce a new type of plot derived from MNE's "TimeViewer", where you can not only skim along the time axis through the plotting GUI, but also along the frequency (and maybe the epochs) axis. After trying out some stuff, my best intuition to reaching this goal would be to simplify the "TimeViewer" class, and make it some kind of a "AxisViewer" class. This class would allow a developer to decide which axis (or even multiple axes) should be manipulable through the GUI. Yet, this would be only a part of the work, as this does not include the actual plotting function used by SourceTFR, and also would only work for the plots made on surface type source level data (since volume type source level data employs an entirely different plotting GUI). In my opinion, this functionality should rather be added later, so I can now concentrate on the finishing touches of the rest of the project.
One such finishing touch is for example time and memory saving computation of tfr_stockwell, which is for now only available for tfr_morlet and tfr_multitaper. I already made attempts to tackle this problem, and currently try to make it pass the equivalence tests. But this will definitely be one of the things to do this week, as it will have big implications on the practical useability of the function.

Another thing I worked on last week (and will continue to work on this week) was the project page where I'll upload my final results next week. I decided to create a GitHub gist for this purpose, since it is simple and good looking at the same time. Most of the gist is already finished, only the links to the PRs and some direct examples will need to be added there. So I hope, everything will work out this week, and I'll be able to show you a nice conclusion on my Google Summer of Code project until next week.

So, for the last time (this summer?!): Stay tuned!

Podcast.__init__: Security, UX, and Sustainability For The Python Package Index

$
0
0
PyPI is a core component of the Python ecosystem that most developer's have interacted with as either a producer or a consumer. But have you ever thought deeply about how it is implemented, who designs those interactions, and how it is secured? In this episode Nicole Harris and William Woodruff discuss their recent work to add new security capabilities and improve the overall accessibility and user experience. It is a worthwhile exercise to consider how much effort goes into making sure that we don't have to think much about this piece of infrastructure that we all rely on.

Summary

PyPI is a core component of the Python ecosystem that most developer’s have interacted with as either a producer or a consumer. But have you ever thought deeply about how it is implemented, who designs those interactions, and how it is secured? In this episode Nicole Harris and William Woodruff discuss their recent work to add new security capabilities and improve the overall accessibility and user experience. It is a worthwhile exercise to consider how much effort goes into making sure that we don’t have to think much about this piece of infrastructure that we all rely on.

Announcements

  • Hello and welcome to Podcast.__init__, the podcast about Python and the people who make it great.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With 200 Gbit/s private networking, scalable shared block storage, node balancers, and a 40 Gbit/s public network, all controlled by a brand new API you’ve got everything you need to scale up. And for your tasks that need fast computation, such as training machine learning models, they just launched dedicated CPU instances. Go to pythonpodcast.com/linode to get a $20 credit and launch a new server in under a minute. And don’t forget to thank them for their continued support of this show!
  • You listen to this show to learn and stay up to date with the ways that Python is being used, including the latest in machine learning and data analysis. For even more opportunities to meet, listen, and learn from your peers you don’t want to miss out on this year’s conference season. We have partnered with organizations such as O’Reilly Media, Dataversity, Corinium Global Intelligence, and Data Counsil. Upcoming events include the O’Reilly AI conference, the Strata Data conference, the combined events of the Data Architecture Summit and Graphorum, and Data Council in Barcelona. Go to pythonpodcast.com/conferences to learn more about these and other events, and take advantage of our partner discounts to save money when you register today.
  • Visit the site to subscribe to the show, sign up for the newsletter, and read the show notes. And if you have any questions, comments, or suggestions I would love to hear them. You can reach me on Twitter at @Podcast__init__ or email hosts@podcastinit.com)
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
  • Join the community in the new Zulip chat workspace at pythonpodcast.com/chat
  • Your host as usual is Tobias Macey and today I’m interviewing Nicole Harris and William Woodruff about the work they are doing on the PyPI service to improve the security and utility of the package repository that we all rely on

Interview

  • Introductions
  • How did you get introduced to Python?
  • Can you start by sharing how you each got involved in working on PyPI?
    • What was the state of the system at the time that you first began working on it?
  • Once you committed to working on PyPI how did you each approach the process of identifying and prioritizing the work that needed to be done?
    • What were the most significant issues that you were faced with at the outset?
  • How often have the issues that you each focused on overlapped at the cross section of UX and security?
    • How do you balance the tradeoffs that exist at that boundary?
  • What is the surface area of the domains that you are each working in? (e.g. web UI, system API, data integrity, platform support, etc.)
    • What are some of the pain points or areas of confusion from a user perspective that you have dealt with in the process of improving the platform?
  • What have been the most notable features or improvements that you have each introduced to PyPI?
    • What were the biggest challenges with implementing or integrating those changes?
  • How do you approach introducing changes to PyPI given the volume of traffic that it needs to support and the level of importance that it serves in the community?
  • What are some examples of attack vectors that exist as a result of the nature of the PyPI platform and what are you most concerned by?
  • How does poor accessibility or user experience impact the utility of PyPI and the community members who interact with it?
  • What have you found to be the most interesting/challenging/unexpected aspects of working on Warehouse?
    • What are some of the most useful lessons that you have learned in the process?
  • What do you have planned for future improvements to the platform?
    • How can the listeners get involved and help out?
  • How was this work funded?

Keep In Touch

  • Nicole
    • @nlhkabu on Twitter
    • Website
    • If you’re using CI to upload to PyPI and would like to speak with Nicole please book a time here
    • If you’re using assistive technology and would like to speak with Nicole please book a time here
  • William
    • @8x5clPW2
    • Website
    • Email
    • Please get in touch if you’d like to work with Trail of Bits on your next security project!

Picks

Links

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA

PSF GSoC students blogs: Week-12: Developing Analytical Web Apps

PSF GSoC students blogs: Seventh Blog - GSOC 2019

$
0
0

Hey! welcome back.

As I mentioned in my previous blog, internet services were paused here in J&K, India. And internet is not back yet. But somehow I have internet access, and its a long story(see previous blog). 

Lets come to main point. I was working on the cheatsheet and was fixing some landing page bugs when internet stopped working here. After that I somehow managed to finish those changes.

Then a week ago I started working on the documentation page. I finished the working prototype of that a few days ago and right now mentors are reviewing that. 

In the meanwhile I am trying to implement the documentation section. Originally I had to use opensource CMS, Strapi  which will manage all our content and documentation page was to made separate from rest of the website and has to be generated through API. But since time is less mentors decided to leave that for later. So, right now I am creating that page within the main repo and after that when it is complete, I will start working on Strapi and then separate this documentation section from the main menu.

PSF GSoC students blogs: Blogpost: 12th week of GSoC (Aug 12 - Aug 18)

$
0
0

The final week of Google Summer of Code is almost here. Time to make some final adjustmens and wrap up the project.

What are the major achievements?

  1. phase-coherence beta coefficinets are computed for euch subject in a dataset.
  2. bootstrap-t (compute t-values for bootstrap sample of phase-coherence betas).
  3. tranform to f-values.
  4. find clusters with arbitrary threshold (for instance an F-value equivalent to an effect significnat at 0.05) and record cluster mass (sum of F values within a cluster) an create H0.
  5. threshold the observed clusters (from orinal data) based on there mass using this distribution.
  6. visualize "significant" clsuters.

What still needs to be done.

Intergation into MNE's API.

 

PSF GSoC students blogs: Google Summer of Code with Nuitka 6th Blog Post

$
0
0

This week, I focused mostly on bug fixes and improving my PyPI-pytest automation script while also working on adding more standalone tests.

  1. I created a pull request https://github.com/Nuitka/Nuitka/pull/483 to add support for py_modules compilation support in Nuitka. The pull request turned out very well, adding support for not only py_modules compilation but also the combination of package and module. In addition, a new distutil example was also added to showcase the compilation of package and module

  2. In the process of the above pull request, I discovered a regression in Nuitka and https://github.com/Nuitka/Nuitka/pull/487 was created as a hotfix.

  3. In addition, Issue https://github.com/Nuitka/Nuitka/issues/479 is fixed by #483 and is now closed

  4. I continued to improve my PyPI-pytest automated testing script, including functional improvements, minor speed improvements, readability, and documentation improvements. My work could be found at https://github.com/Nuitka/Nuitka/pull/495.

  5. More standalone tests were also added to my pull request at https://github.com/Nuitka/Nuitka/pull/484. This is a side goal and is less important

 

I am very proud of the work I have done this week. The goal for this final week is to finish up pull request #495, and I plan on finishing #484 after GSoC ends. I also discussed with my mentor and plan on working for Nuitka long term, even after GSoC :). 


 

PSF GSoC students blogs: See you later PSF-GSoC

$
0
0

Hi everyone!

"""

The truth was that it was an incredible experience I recommend it
Anyone who likes challenges in new technologies,
development and especially python.

Work under the supervision of titans such as PSF and Google
It gives an interesting boost.
Thank you for supporting the development of the potential of
people.

As for work, the second stage was complicated enough for me
I was running out of time and my lack of knowledge complicated
even more, set aside the web service testing by the client test of pyafipws that for now is more important for the project.

I will continue working on my knowledge,
A lot of ink remains in the inkwell.

I want to thank my mentors for the support,
to this beautiful community that is PyAr,
to all the participants of Gsoc-2019 I hope you had a great experience,
to sounak98 you did a great job on the blog,
to the botanic for being aware of us,
and of course,
to the administrators :!: team-psf / \ team-gsoc :!: for having followed up and marked the development, which was very important for our performance.

To improve my knowledge I could not have had more luck working with the pyafipws project, seeing the code you can see the great handling of the python language, it runs through it and being complex at the same time, with which you can learn a lot about the management of it and its tools, my congratulations to Mariano Reingart the author / maintainer of this opensource project.

I don't want to leave the opportunity to mention an excellent book,
which is so far the best one I read and which has become  author In my referent, very complete, extraordinary handling of the writing and explanation connecting all topics, using experiences and problems of my own in work done and the star is 'dive in to Python3' its author Mark Pilgrim, to whom I give my thanks.
and to the translator of his Spanish version Jose Miguel Gonzalez Aguilera.
PS: that you have read it does not mean that you have learned :)

Well, I leave you. I have to finish the tests!

"""

Regards and Good Life!


PSF GSoC students blogs: Working towards pre-planned transforms

$
0
0

What did you do this week?

The main feature I've been working on this week has been adding pre-planned transforms to pypocketfft in (pypocketfft!28). This will allow users to speed-up cases where many transforms of the same shape are done, without needing to rely on any internal caches. This gives the users a small performance improvement in pypocketfft but adding this to the scipy.fft interface will also allow other backends to benefit. e.g. pyFFTW can have a significantly more expensive planning phase.

Plans have now been added into the c++ interface of pypocketfft but I have still got to expose these in the python interface. Additionally, I've made a number of other contributions in several other places:

  • Refactored the real transform tests to use pytest and to test all the transforms in long double precision as well (scipy#10669)
  • Fixed a race condition in my custom threadpool code that was causing crashes on macOS (pypocketfft!27)
  • Added benchmarks to my multithreading PR (scipy#10614)
  • Opened an issue in mkl_fft about adding a scipy.fft interface (mkl_fft#42). Unfortunately, mkl_ffl doesn't seem to be very active and the issue hasn't received any response yet.
  • Fixed a compile warning in uarray (uarray#195)

What is coming up next?

The coding period has officially ended and it's now time to "submit the code". Most of my code has already been merged into the SciPy master branch so this will just involve writing a summary of my work over the whole GSoC project.

I would also like to finish up the pre-planned transform code but it's likely too late to get this merged in time for the evaluation.

Did you get stuck anywhere?

Fixing the race condition in pypocketfft was quite challenging. The only symptom was a SEGFAULT that occurred only rarely and only on macOS, a platform which I don't use and so couldn't reproduce the issue locally. This made diagnosing and solving the issue very tricky. Thankfully, Martin (pypocketfft's author) had access to apple hardware and was eventually able to give me enough details that I found an issue from another project that had run into almost exactly the same issue.

 

PSF GSoC students blogs: Week 10 & 11

$
0
0

These two weeks, I've been working on fixing bug #1. I think my algorithm will work in general, but right now the get_cves function doesn't work as I expected, which would cause some problem with data format in futher. Previously, the function will run the query that selects all the version of a product_vendor pair, and then save the result in memory, and using Python code to check whether the version we want is in it. This is actually inefficient and memory-consuming. Therefore, I refactored the code for conducting the query. Right now, the query will only select the version we want and return it to memory. The time for running the whole test cases reduced from 83 seconds to 61 second. So right now, I will try to implement the dynamic programming method and see if the time complexity is not too high.

Codementor: Top 9 Django Concepts - Part 2 : 5 Mins

$
0
0
The 2nd part of a 3 part series on 9 concepts of Django to help any aspiring Django developer to accelerate their learnings

PSF GSoC students blogs: weeklyCheckIn[12]

$
0
0

What did I do this week?

Last week, me and my mentor started testing mscolab. At first, I exposed my port through ngrok. But the network I/O were extremely slow. I couldn't demonstrate all of mscolab's features. Then we setup an AWS instance with mscolab server deployed. We could test and improve on many of its features. Some things I worked on this week:

  1. Adding support to use Postgres
  2. Refactoring tests, so that the library code is independent of test configurations.
  3. Adding newly created projects to project-list, in real time
  4. Add newly permitted collaborators to users-list in project window, in real time.
  5. Fix autosave inconsistency when projects are switched

What's coming up next?

There are very few development tasks remaining. Since this is the last week of GSoC, I'd be working on documenting the code I've written, externally. That would take most of my time this week.

Did I get stuck anywhere?

Yes, I got stuck in a bad place for some-time this week. While setting up Postgres, I had to manually autoincrement sequence to assign 'id' to tables, if I explicitly insert rows. I have documented the issue and solution in this blogpost if you're interested in learning more about it.

Test and Code: 84: CircuitPython - Scott Shawcroft

$
0
0

Adafruit enables beginners to make amazing hardware/software projects.
With CircuitPython, these projects can now use Python.

The combination of Python's ease of use and Adafruit's super cool hardware and a focus on a successful beginner experience makes learning to write code that controls hardware super fun.

In this episode, Scott Shawcroft, the project lead, talks about the past, present, and future of CircuitPython, and discusses the focus on the beginner.

We also discuss contributing to the project, testing CircuitPython, and many of the cool projects and hardware boards that can use CircuitPython, and Blinka, a library to allow you to use "CircuitPython APIs for non-CircuitPython versions of Python such as CPython on Linux and MicroPython," including Raspberry Pi.

Special Guest: Scott Shawcroft.

Sponsored By:

Links:

<p>Adafruit enables beginners to make amazing hardware/software projects.<br> With CircuitPython, these projects can now use Python.</p> <p>The combination of Python&#39;s ease of use and Adafruit&#39;s super cool hardware and a focus on a successful beginner experience makes learning to write code that controls hardware super fun.</p> <p>In this episode, Scott Shawcroft, the project lead, talks about the past, present, and future of CircuitPython, and discusses the focus on the beginner.</p> <p>We also discuss contributing to the project, testing CircuitPython, and many of the cool projects and hardware boards that can use CircuitPython, and Blinka, a library to allow you to use &quot;CircuitPython APIs for non-CircuitPython versions of Python such as CPython on Linux and MicroPython,&quot; including Raspberry Pi.</p><p>Special Guest: Scott Shawcroft.</p><p>Sponsored By:</p><ul><li><a href="https://www.patreon.com/testpodcast" rel="nofollow">Patreon Supporters</a>: <a href="https://www.patreon.com/testpodcast" rel="nofollow">Help support the show with as little as $1 per month and be the first to know when new episodes come out.</a></li></ul><p>Links:</p><ul><li><a href="https://circuitpython.org/" title="CircuitPython" rel="nofollow">CircuitPython</a></li><li><a href="https://circuitpython.org/downloads" title="Downloads" rel="nofollow">Downloads</a> &mdash; All the products that run CircuitPython</li><li><a href="https://learn.adafruit.com/category/circuitpython" title="Learning Guides with CircuitPython" rel="nofollow">Learning Guides with CircuitPython</a></li><li><a href="https://learn.adafruit.com/adafruit-circuit-playground-express/circuitpython-quickstart" title="Loading CircuitPython on Circuit Playground Express" rel="nofollow">Loading CircuitPython on Circuit Playground Express</a></li><li><a href="https://adafru.it/discord" title="Adafruit Discord Server" rel="nofollow">Adafruit Discord Server</a></li><li><a href="https://twitter.com/tannewt" title="Scott Shawcroft (@tannewt) / Twitter" rel="nofollow">Scott Shawcroft (@tannewt) / Twitter</a></li><li><a href="https://pypi.org/project/Adafruit-Blinka/" title="Adafruit-Blinka " rel="nofollow">Adafruit-Blinka </a></li></ul>

Continuum Analytics Blog: Enterprises Need to Think Differently about Data Science. Here’s How.

PSF GSoC students blogs: Weekly Check-in #13 : ( 16 Aug - 22 Aug )

$
0
0

What did you do this week?

  • I worked on getting Travis to push releases automatically to PyPI, adding a new `ROBOTSTXT_USER_AGENT` setting in Scrapy, and improvements to SitemapSpider.

What is coming up next?

  • I am going to work on the final PSF blog post in which I will focus on my experience of GSoC 2019 working with my awesome mentors, and Scrapy.
  • Next, I will write a final report for third evaluation of Google Summer of Code.
  • Next up, I will work on the changes suggested on my this week's work.

Did you get stuck anywhere?

  • Nothing Major.

PyCon: PyCon 2020 Conference Site is here!

$
0
0


After 2 successful years in Cleveland, OH, PyCon 2020 and PyCon 2021 will be
moving to Pittsburgh, PA!


Head over to us.pycon.org/2020 to check out the look for PyCon 2020.

Our bold design includes the Roberto Clemente Bridge, also known as the Sixth Street Bridge, which spans the Allegheny River in downtown Pittsburgh. The Pittsburgh Steelmark, was originally created for United States Steel Corporation to promote the attributes of steel: yellow lightens your work; orange brightens your leisure; and blue widens your world. The PPG Building, is a complex in downtown Pittsburgh, consisting of six buildings within three city blocks and five and a half acres. Named for its anchor tenant, PPG Industries, who initiated the project for its headquarters, the buildings are all of matching glass design consisting of 19,750 pieces of glass. Also included in the design are a fun snake, terminal window, and hardware related items.

Sponsor Opportunities

Sponsors help keep PyCon affordable and accessible to the widest possible audience. Sponsors are what make this conference possible. From low ticket prices to financial aid, to video recording, the organizations who step forward to support PyCon, in turn, support the entire Python community. They make it possible for so many to attend, for so many to be presenters, and for the people at home to watch along.

As with any sponsorship, the benefits go both ways. Organizations have many options for sponsorship packages, and they all benefit from exposure to an ever growing audience of Python programmers, from those just getting started to 20 year veterans and every walk of life in between. If you're hiring, the Job Fair puts your organization within reach of a few thousand dedicated people who came to PyCon looking to sharpen their skills.

For more details on sponsorship opportunities go to the Sponsor Prospectus. If you are interested in becoming a PyCon sponsor go to the application form.

We look forward to sharing more news on the call for proposals, financial aid applications, registration, and more, so stay tuned! Also follow us here on the PyCon Blog and @PyCon on Twitter.

Real Python: Python Histogram Plotting: NumPy, Matplotlib, Pandas & Seaborn

$
0
0

In this course, you’ll be equipped to make production-quality, presentation-ready Python histogram plots with a range of choices and features.

If you have introductory to intermediate knowledge in Python and statistics, then you can use this article as a one-stop shop for building and plotting histograms in Python using libraries from its scientific stack, including NumPy, Matplotlib, Pandas, and Seaborn.

A histogram is a great tool for quickly assessing a probability distribution that is intuitively understood by almost any audience. Python offers a handful of different options for building and plotting histograms. Most people know a histogram by its graphical representation, which is similar to a bar graph:

Histogram of commute times for 1000 commuters

This course will guide you through creating plots like the one above as well as more complex ones. Here’s what you’ll cover:

  • Building histograms in pure Python, without use of third party libraries
  • Constructing histograms with NumPy to summarize the underlying data
  • Plotting the resulting histogram with Matplotlib, Pandas, and Seaborn

Free Bonus: Short on time? Click here to get access to a free two-page Python histograms cheat sheet that summarizes the techniques explained in this tutorial.


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Catalin George Festila: Python Qt5 - the QTimer class.

$
0
0
I haven't written about PyQt5 in a while and today I decided to add a short tutorial on this python module. The QTimer class is a high-level programming interface for timers and provides repetitive and single-shot timers. I this example I call a method every second with these lines: self.timer = QTimer() self.timer.timeout.connect(self.handleTimer) self.timer.start(1000)

PyCoder’s Weekly: Issue #382 (Aug. 20, 2019)

$
0
0

#382 – AUGUST 20, 2019
View in Browser »

The PyCoder’s Weekly Logo


An Effective Python Environment: Making Yourself at Home

This guide will walk you through the decisions you need to make when customizing your development environment for working with Python: shells, terminal emulators, version management (pyenv), virtual environments & pipenv, package management, and more.
REAL PYTHON

Python Static Analysis at Scale: An Instagram Story

Instagram’s back-end is a massive Django app with several million lines of code. This post is about how they’ve used linting and automated refactoring to help manage the scale of their Python codebase.
BENJAMIN WOODRUFF (INSTAGRAM)

Automated Python Code Reviews, Directly From Your Git Workflow

alt

Take the hassle out of code reviews - Codacy flags errors so you can fix them quickly. Address security concerns, duplication, complexity, drops in coverage, and style violations before you merge. Integrates seamlessly with GitHub, Bitbucket, and GitLab →
CODACYsponsor

Writing Custom Profilers for Python

In this article you’ll learn how to write custom profilers, and in particular profilers that will help you pinpoint the places in your code where it just sits there waiting.
ITAMAR TURNER-TRAURING

Python Web Frameworks Overview List

Django, Flask, Pyramid, and many, many others—get an overview of what’s available so you can choose the right Python framework for your web development project.
STXNEXT.COM

Designing Continuous Build Systems: Handling Webhooks With Sanic

How to use Python and Sanic to handle webhook events from GitHub in continuous build systems.
CHRISTIAN MEDINA• Shared by Cristian Medina

PyCon US 2020 Website is Live

PyCon 2020 takes place April 15–23, 2020 in Pittsburgh, PA.
PYCON.ORG

Discussions

Python Jobs

Senior Backend Software Engineer (Remote)

Close

Senior Python Developer (Austin, TX)

InQuest

Backend and DataScience Engineers (London, Relocation & Visa Possible)

Citymapper Ltd

Software Engineering Lead, Python (Houston, TX)

SimpleLegal

Software Engineer (Multiple US Locations)

Invitae

Python Software Engineer (Munich Germany)

Stylight GmbH

Senior Software Developer (Edmonton, AB)

Levven Electronics Ltd.

Lead Data Scientist (Buffalo, NY)

Utilant LLC

More Python Jobs >>>

Articles & Tutorials

Data Cleaning Using Python & Pandas

Learn how to do simplify your data preprocessing work using the Pyjanitor package. More specifically, you’ll learn how to: Add a column to a Pandas dataframe, remove missing values, remove an empty column, and clean up column names.
ERIK MARSJA

Python Histogram Plotting: NumPy, Matplotlib, Pandas & Seaborn

Get equipped to make production-quality, presentation-ready Python histogram plots with a range of choices and features. It’s your one-stop shop for constructing and manipulating histograms with Python’s scientific stack.
REAL PYTHONvideo

Slack <3 Python

alt

Slack Python SDK v2 is now available to help you build Slack apps faster with less complexity. Built for Python 3, you can now use new features (like type hints and return types) to help you accomplish more while coding less. Looking for a tutorial or migration guide? It all lives here →
SLACKsponsor

Python for LEGO EV3

“You can now use your EV3 Brick to unleash the power of Python programming using MicroPython. Simply install the EV3 MicroPython image onto any micro SD card and boot up your EV3 Brick from it to start programming straight away.”
LEGO.COM• Shared by Python Bytes FM

How to Make a Discord Bot in Python

Learn how to make a Discord bot in Python and interact with several APIs. See how to handle events, accept commands, validate and verify input, and all the basics that can help you create useful and exciting automations!
REAL PYTHON

Bridging Node.js and Python With PyNode to Predict Home Prices

“In this article I demonstrate a novel Node.js package named PyNode used to invoke Python code within a Node.js application and, more importantly, receive Python return types in the calling Node.js application.”
ADAM MCQUISTAN

Python Now Supported in Azure Functions

Python support for Azure Functions is now generally available and ready to host your production workloads across data science and machine learning, automated resource management, and more.
MICROSOFT.COM

150+ Business Data Science Application Ideas in Python

A curated list of practical business machine learning (BML) and business data science (BDS) applications for Accounting, Customer, Employee, Legal, Management and Operations.
GITHUB.COM/FIRMAI

Super Easy Python CLIs With Click

How to give your Python scripts a full-featured Command-Line Interface (CLI) using the click library.
RICHARD BARELLA

Simple Scene Boundary/Shot Transition Detection With OpenCV

Learn how to implement a simple scene boundary and shot transition detector with OpenCV and Python.
ADRIAN ROSEBROCK

Software Defined Network and the OpenFlow Protocol

Explains a simple implementation of a switching hub using software defined networking with Python.
REBECA SARAI

Python 3 at Mozilla

How far along has Mozilla come in the Python 3 migration?
ANDREW HALBERSTADT• Shared by Python Bytes FM

Projects & Code

Events

Kiwi PyCon X

August 23 to August 26, 2019
PYTHON.NZ

IndyPy Web Conf 2019

August 23 to August 24, 2019
INDYPY.ORG

PyCon Latam 2019

August 29 to September 1, 2019
PYLATAM.ORG


Happy Pythoning!
This was PyCoder’s Weekly Issue #382.
View in Browser »

alt

[ Subscribe to 🐍 PyCoder’s Weekly 💌 – Get the best Python news, articles, and tutorials delivered to your inbox once a week >> Click here to learn more ]

Learn PyQt: Embedding PyQtGraph (or any other custom PyQt5 widgets) from Qt Designer

$
0
0

Qt Designer is a great tool for designing PyQt5 GUIs, allowing you to use the entire range of Qt5 widgets and layouts to construct your apps. As your applications get more complex however you may find yourself creating custom widgets, or using PyQt5 libraries such as PyQtGraph, who's widgets are not available within Designer.

Helpfully, Qt Designer supports a mechanism for using placeholder widgets to represent your custom or external widgets in your design. This tutorial will walk you through the process of using placeholders to include a PyQtGraph plot in your app from within Qt Designer.

Promoting Widgets

The principle of using placeholders in Qt Designer is quite straightforward — 

  1. Create a UI as normal in Qt Designer.
  2. Add a placeholder widget to represent the custom widget you're adding.
  3. Tell Qt to replace your placeholder with your actual widget when building the UI.

In Qt this final step is referred to as promoting (as in promoting a base class).

If the custom widget you are adding is a subclass of an existing Qt widget, you may want to use the base class as your placeholder to promote from. For example, if you have a custom MyAwesomeButton button widget subclassed from QPushButton use QPushButton as the placeholder and promote it to MyAwesomeButton. This gives you access to the base class properties, events and actions from within Qt Designer.

If you don't have an obvious base class to use, then you can use QWidget, the common base class of all Qt widgets.

PyQtGraph

Data science is one of the post popular uses of Python, and building dashboards and analysis tools is a common use case of PyQt5. For all of these being able to add plots to your UI is very useful — and being able to do this from Qt Designer even more so.

There are a number of plotting libraries available in Python, with matplotlib being the most popular and offering some basic support for PyQt5. PyQtGraph is an popular alternative which uses Qt's native QGraphicsScene to provide fast zooming, scaling, drag-drop behaviour that feels a natural part of your application.

Whether you're using PyQtGraph or maplotlib for your plotting needs, the plot canvas widgets are not available from within Qt Designer. In this tutorial I'll walk you through the process of using these custom widgets in your apps.

If you don't have PyQtGraph installed already, you can install it using:

pip install pyqtgraph

The instructions below aren't specific to PyQtGraph, and you can use the same process to add matplotlib or any other custom widgets to your app.

Qt Designer

We will be using Qt Designer to create a simple UI design, and adding a placeholder for our PyQtGraph widget. First open Qt Designer and create a new QMainWindow as normal.

Qt Creator — Select MainWindow for widget type Qt Creator — Select MainWindow for widget type

We next need to add the placeholder widget. As there is no suitable baseclass for the PyQtGraph plot widget, we'll use the basic QWidget as our placeholder. Select the Widget from the left sidebar and place it in the centre of your window.

Give the widget a name, "graphWidget" will do. This is just a tag to reference the element in code.

Add a widget to the window. Name the widget as Add a widget to the window. Name the widget as "graphWidget"

Right click on the widget and select Promote to from the widget's context menu.

Promoting a QWidget indicates that it should be replaced with the specified subclass, in our case the PyQtGraph plot widget.

A promoted widget can be reverted back to its base class by right-clicking and choosing Demote to from the widget's context menu.

Right click to show the promotion menu Right click to show the promotion menu

You will be presented with a dialog to specify the custom widget class the placeholder widget will become.

The header file is the name of the Python module used to import the class, which is pyqtgraph. Specify PlotWidget as the class name of the widget to replace it with.

Promote the widget by specifying the class name as PlotWidget and header file as pyqtgraph. Promote the widget by specifying the class name as PlotWidget and header file as pyqtgraph.

The name you use for the file doesn't matter, but it's usually a good idea to name it after the class you're going to create with it.

Voila! The widget is now promoted to a canvas to plot. But you won't be able to see any changes within Qt Designer. Save the window as mainwindow.ui in the same directory as your PyQt app.

For a complete guide to using Qt Designer .ui files from Python check out First steps with Qt Creator.

Loading the .ui file

We now have the mainwindow.ui file containing our UI definition. We can load this from Python to show the window and our custom widget.

Let's start from a basic app template.

python
fromPyQt5importQtWidgets,uicimportpyqtgraphaspgimportsysclassMainWindow(QtWidgets.QMainWindow):def__init__(self,*args,**kwargs):super(MainWindow,self).__init__(*args,**kwargs)#Load the UI Pageuic.loadUi('mainwindow.ui',self)defmain():app=QtWidgets.QApplication(sys.argv)main=MainWindow()main.show()sys.exit(app.exec_())if__name__=='__main__':main()

Save the code above in the same folder as your mainwindow.ui file, and run it as normal.

python3 my_app.py
Your graph is now embedded Your graph is now embedded

You should see a window with your widget transformed into a PyQtGraph plotting widget.

Let's now create a function to make a simple plot of x and y data.

python
fromPyQt5importQtWidgets,uicfrompyqtgraphimportPlotWidget,plotimportpyqtgraphaspgimportsys# We need sys so that we can pass argv to QApplicationimportosclassMainWindow(QtWidgets.QMainWindow):def__init__(self,*args,**kwargs):super(MainWindow,self).__init__(*args,**kwargs)#Load the UI Pageuic.loadUi('mainwindow.ui',self)self.plot([1,2,3,4,5,6,7,8,9,10],[30,32,34,32,33,31,29,32,35,45])defplot(self,hour,temperature):self.graphWidget.plot(hour,temperature)defmain():app=QtWidgets.QApplication(sys.argv)main=MainWindow()main.show()sys.exit(app.exec_())if__name__=='__main__':main()

So we added the plot() method which accepts two arrays, tempTemperature and hourHour, then plots the data using the graph widget.plot() method.

Run the code, you should see the following.

The custom PyQtGraph widget showing dummy data. The custom PyQtGraph widget showing dummy data.

That's it! You have just embedded your first plot with PyQtGraph.

The default PyQtGraph plot isn't very pretty, however can play around with the .plot() call to change the data shown.

We'll cover more complex PyQtGraph plots and plot customization, including line colours, styles and alternative types of plots in an upcoming tutorial.

Viewing all 22872 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>