Python for Beginners: Create Decorators Using Classes in Python

Planet Python - Wed, 2022-01-12 08:55

You might be knowing how to create decorators in python using functions. In this article, we will discuss ways to create decorators using classes in Python. First we will discuss what are callable objects and then we will implement decorators using those callable objects by defining classes for them.

Table of Contents
  1. What are Callable Objects?
  2. How to create decorators using classes?
    1. Create Decorators by passing functions as arguments to the class constructor
    2. Create decorators by using @ sign 
  3. Conclusion
What are Callable Objects?

Any object in python that can be called just like functions and methods is called a callable object. In python every callable object has an implementation of the __call__() method in its class definition. We can say that any object that has the __call__() method in its class definition is called a callable object. 

To call an object, we need to implement the __call__() method in the class definition of the object.

For example, look at the following source code.

class Car: def __init__(self): self.brand = "Tesla" self.speed = "100mph" def __call__(self, *args, **kwargs): print("Called me? I am coming at {} speed.".format(self.speed))

Here, we have defined a class named Car. Apart from its constructor definition, we have also defined the __call__() method in its class definition. Now we can call any instance of the Car class and the __call__() method will be executed as follows.

class Car: def __init__(self): self.brand = "Tesla" self.speed = "100mph" def __call__(self, *args, **kwargs): print("Called me? I am coming at {} speed.".format(self.speed)) # create callable object myCar = Car() # call myCar myCar()


Called me? I am coming at 100mph speed.

We can use any callable object that accepts a function or a callable object as input and returns a callable object or a function to implement python decorators.

How to create decorators using classes?

We can create decorators using classes by defining callable objects using the __call__() method, which we will discuss in this section.

First, we will define a function add() that takes two numbers as input and prints their sum. 

def add(num1, num2): value = num1 + num2 print("The sum of {} and {} is {}.".format(num1, num2, value)) # execute add(10, 20)


The sum of 10 and 20 is 30.

Now, we have to define a decorator in such a way that the add() function should also print the product of the numbers along with the sum. For this, we can create a decorator class.

We can implement the __call__() method inside a class to implement the decorators.

First, we will define the constructor of the decorator_class that accepts the add() function as an input parameter and assigns it to a class variable func.

Then we will implement the __call__() method. The code inside the __call__() method will calculate the product of the input numbers and will print it. After that, it will call the input function add() with the given input numbers. At last, it will return the value returned by the add() function.

class decorator_class: def __init__(self, func): self.func = func def __call__(self, *args): product = args[0] * args[1] print("Product of {} and {} is {} ".format(args[0], args[1], product)) return self.func(args[0], args[1])

Inside the __call__() method, we have implemented the code that prints the product of the numbers that are given as input and then returns the output of the add() function after calling it. The add() function prints the sum of the input numbers. As we have defined the function and the decorator class, let us see how we can use them.

Create Decorators by passing functions as arguments to the class constructor

To create a decorated function, We can pass the add() function as an input argument to the constructor of the decorator class. The add() function will be assigned to the func variable in the decorator_class. Once an instance of the decorator_class is called, it will execute the code inside the __call__() method to print the product of the input numbers. Then it will return the output of the function func after calling it. As the add() function has been assigned to func, it will print the sum of the numbers.

class decorator_class: def __init__(self, func): self.func = func def __call__(self, *args): product = args[0] * args[1] print("Product of {} and {} is {} ".format(args[0], args[1], product)) return self.func(args[0], args[1]) def add(num1, num2): value = num1 + num2 print("The sum of {} and {} is {}.".format(num1, num2, value)) # execute decorator_object = decorator_class(add) decorator_object(10, 20)


Product of 10 and 20 is 200 The sum of 10 and 20 is 30. Create decorators by using @ sign 

Instead of passing the add function to the class constructor, we can specify decorator_class name with @ sign before the definition of the add() function. After this, whenever the add() function is called, It will always print both the product and sum of the input numbers.

class decorator_class: def __init__(self, func): self.func = func def __call__(self, *args): product = args[0] * args[1] print("Product of {} and {} is {} ".format(args[0], args[1], product)) return self.func(args[0], args[1]) @decorator_class def add(num1, num2): value = num1 + num2 print("The sum of {} and {} is {}.".format(num1, num2, value)) # execute add(10, 20)


Product of 10 and 20 is 200 The sum of 10 and 20 is 30.

In this method, there is a drawback that you cannot use the add() function to just add the numbers while defining decorated functions using @ sign. It will always print the product of the numbers along with their sum. So,If you are using the add() function at any other place in its original form, it will cause an error.


In this article, we have discussed ways to create python decorators using classes in Python. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

The post Create Decorators Using Classes in Python appeared first on PythonForBeginners.com.

Categories: FLOSS Project Planets

Results from the first new members campaign

Open Source Initiative - Wed, 2022-01-12 08:30

We did it! We’re welcoming 1,354 new members to the Open Source Initiative. The membership drive we launched at the end of 2021 surpassed our expectations. These new members are mostly “free” members and don’t have voting rights to elect the next board members; however, there is time to become a full member by the next election cycle in March.

Quick facts about the campaign

The campaign was the first of its kind. For starters we introduced a new membership level with a zero cost with the intention to reach out to people who are not able or in a position to pay for membership. We recognize that $40 can be a lot of money in many parts of the world.

The campaign ran on a purpose-built minisite instead of the main site because we needed speed to execute the campaign. Modifying Drupal would have been more complicated. The new members badges proved to be popular: we’re studying ways to make them available inside the member pages as a permanent feature.

Thanks to Plausible.io we tracked results of the campaign without invading users’ privacy. The full results are publicly accessible and a summary is below:

  • 5k unique visitors
  • 54% bounce rate
  • 4k referrals from opensource.org banner!
  • 67% traffic from mobile (28% desktop)
  • 27% overall signup conversion rate
  • 600 unique visitors downloaded the PNG badge (500 downloaded the svg version)
Relative geographic distribution of signupsTrend of visitors for the campaign

A special mention should go to traffic via social media. Lots of people tend to overestimate the effect of promotions on these channels.

Top sources of traffic to campaign minisiteLessons learned and next steps

The majority of traffic to the campaign was through the website, with social media traffic being quite small by comparison. The impact of social media on promotions like this is often overestimated. Social channels are great for engaging with the community, “reinforcing the brand”, and connecting with “influencers”: basically, social media helps make people aware that we exist, but isn’t a particularly effective tool to convince them to take an action. Therefore, we’ll emphasize our website for future promotions, and social media channels will continue to be a part of the promotional mix, but not the primary focus.

As for next steps, our next campaign will be focused on encouraging our new free members to convert to voting members so that everyone's voice can be heard. Our next election is in March 2022. Stay tuned for more.

if(window.strchfSettings === undefined) window.strchfSettings = {};window.strchfSettings.stats = {url: "https://open-source-initiative.storychief.io/results-from-the-first-new-members-campaign?id=1883100141&type=3",title: "Results from the first new members campaign",id: "d41e8c3e-e034-48f3-84d1-20372c1b1028"};(function(d, s, id) {var js, sjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {window.strchf.update(); return;}js = d.createElement(s); js.id = id;js.src = "https://d37oebn0w9ir6a.cloudfront.net/scripts/v0/strchf.js";js.async = true;sjs.parentNode.insertBefore(js, sjs);}(document, 'script', 'storychief-jssdk'))
Categories: FLOSS Research

Quansight Labs Blog: IPython 8.0, Lessons learned maintaining software

Planet Python - Wed, 2022-01-12 08:00

This is a companion post from the Official release of IPython 8.0, that describe what we learned with this large new major IPython release. We hope it will help you apply best practices, and have an easier time maintaining your projects, or helping other. We'll focus on many patterns that made it easier for us to make IPython 8.0 what it is with minimal time involved.

Read more… (8 min remaining to read)

Categories: FLOSS Project Planets

Python Circle: Django vs Node.js: Which One Is Better for Web Development?

Planet Python - Wed, 2022-01-12 05:40
Benefits of using Django and Node.js, Django vs Node.js: Which One Is Better for Web Development?, Basic features of Django and Node.js, Drawbacks of using Django and Node.js
Categories: FLOSS Project Planets

Kay Hayen: Nuitka Release 0.6.19

Planet Python - Wed, 2022-01-12 04:51

This is to inform you about the new stable release of Nuitka. It is the extremely compatible Python compiler, “download now”.

This release adds support for 3.10 while also adding very many new optimization, and doing a lot of bug fixes.

Bug Fixes
  • Calls to importlib.import_module with expressions that need releases, i.e. are not constant values, could crash the compilation. Fixed in already.

  • After a fix for the previous release, modules that fail to import are attempted again when another import is executed. However, during this initialization for top level module in --module mode, this was was done repeatedly, and could cause issues. Fixed in already.

  • Standalone: Ignore warning given by patchelf on Linux with at least newer OpenSUSE. Fixed in already.

  • Standalone: Add needed datafile for cv2 package.

  • Fix, need to avoid computing large values out of << operation as well. Fixed in already.

    # This large value was computed at runtime and then if used, also # converted to a string and potentially hashed, taking a long time. 1 << sys.maxint
  • Standalone: Ignore warning given by patchelf on Linux about a workaround being applied.

  • Fix, calls to importlib.import_module were not correctly creating code for dynamic argument values that need to be released, causing the compilation to report the error. Fixed in already.

  • MSYS2: Fix, the console scripts are actually good for it as opposed to CPython, and the batch scripts should not be installed. Fixed in already.

  • Setuptools: Added support older version of setuptools in meta build integration of Nuitka.

  • Fix, calls to importlib.import_module with 2 arguments that are dynamic, were not working at all. Fixed in already.

  • Windows: Compiling with MinGW64 without ccache was not working due to issues in Scons. Fixed in already.

  • Fix, the repr built-in was falsely annotated as producing a str value, but it can be also derived or unicode in Python2.

  • Fix, attribute nodes were not considering the value they are looking up on. Now that more values will know to have the attributes, that was causing errors. Fixed in already.

  • Standalone: Added datafile for cv2 package. Fixed in already.

  • Fix, left shifting can also produce large values and needs to be avoided in that case, similar to what we do for multiplications already. Fixed in already.

  • UI: The new option --disable-ccache didn’t really have the intended effect. Fixed in already.

  • UI: The progress bar was causing tearing and corrupted outputs, when outputs were made, now using proper tqdm API for doing it, this has been solved. Fixed in already.

  • Fix, the constant value sys.version_info didn’t yet have support for its type to be also a compile time constant in e.g. tuples. Fixed in already.

  • Onefile: Assertions were not disabled, and on Windows with MinGW64 this lead to including the C filenames of the zstd inline copy files and obviously less optimal code. Fixed in already.

  • Standalone: Added support for bottle.ext loading extensions to resolve at compile time. Fixed in already.

  • Standalone: Added support for seedir required data file. Fixed in already.

  • MSYS2: Failed to link when using the static libpython, which is also now the default for MSYS2. Fixed in already.

  • Python3.6+: Fix, the intended finalizer of compiled asyncgen was not present and in fact associated to help type. This could have caused corruption, but that was also very unlikely. Fixed in already.

  • Python3: Fix, need to set __file__ before executing modules, as some modules, e.g. newer PyWin32 use them to locate things during their initialization already.

  • Standalone: Handle all PyWin32 modules that need the special DLLs and not just a few.

  • Fix, some .pth files create module namespaces with __path__ that does not exist, ignore these in module importing.

  • Python2.6-3.4: Fix, modules with an error could use their module name after it was released.

  • Distutils: When providing arguments, the method suggested in the docs is not compatible with all other systems, e.g. not setuptools_rust for which a two elemented tuple form needs to be used for values. Added support for that and documented its use as well in the User Manual.

  • Python3.7+: Do no longer allow deleting cell values, this can lead to corruption and should be avoided, it seems unlikely outside of tests anyway.

  • Standalone: Added support for more ciphers and hashes with pycryptodome and pycryptodomex, while also only including Ciphers when needed.

  • Distutils: Was not including modules or packages only referenced in the entry point definition, but not in the list of packages. That is not compatible and has been fixed.

  • Fix, must not expose the constants blob from extension modules, as loading these into a compiled binary can cause issues in this case.

  • Standalone: Added support for including OpenGL and SSL libraries with PySide2 and PySide6 packages.

  • Windows: Fix, the cmd files created for uninstalled Python and accelerated programs to find the Python installation were not passing command line arguments.

  • Windows: Executing modules with --run was not working properly due to missing escaping of file paths.

  • Fix, parsing .pyi files that make relative imports was not resolving them correctly.

  • Python3: Fix, when disabling the console on Windows, make sure the file handles still work and are not None.

  • Windows: Fix, need to claim all OS versions of Windows as supported, otherwise e.g. high DPI features are not available.

New Features
  • Programs that are to be executed with the -m flag, can now be compiled with --python-flag=-m and will then behave in a compatible way, i.e. load the containing package first, and have a proper __package__ value at run time.

  • We now can write XML reports with information about the compilation. This is initially for use in PGO tests, to decide if the expected forms of inclusions have happened and should grow into a proper reporting tool over time. At this point, the report is not very useful yet.

  • Added support for Python 3.10, only match statements are not completely supported. Variantion with | matches that also assign are not allowed currently.

  • Windows: Allow using --clang with --mingw64 to e.g. use the clang.exe that is contained in the Nuitka automatic download rather than gcc.exe.

  • Added support for Kivy. Works through a plugin that is automatically enabled and needs no other inputs, detecting everything from using Kivy at compile time.

  • Added initial support for Haiku OS, a clone of BeOS with a few differences in their Python installation.

  • Added experimental plugin trio that works around issues with that package.

  • Also trust hard imports made on the module level in function level code, this unlocks many more static optimization e.g. with sys.version_info when the import and the use are not on the same level.

  • For the built-in type method calls with generic implementation, we now do faster method descriptor calls. These avoid creating a temporary PyCFunction object, that the normal call slot would, this should make these calls faster. Checking them for compiled function, etc. was only wasteful, so this makes it more direct.

  • Loop and normal merge traces were keeping assignments made before the loop or inside a branch, that was otherwise unused alive. This should enable more optimization for code with branches and loops. Also unused loop traces are now recognized and removed as well.

  • Avoiding merges of escaped traces with the unescaped trace, there is no point in them. This was actually happening a lot and should mean a scalability improvement and unlock new optimization as well.

  • Avoid escaping uninit traces. Unset values need not be considered as potentially modified as that cannot be done.

  • The str shape is now detected through variables, this enables many optimization on the function level.

  • Added many str operation nodes.

    These are specifically all methods with no arguments, as these are very generic to add, introduced a base class for them, where we know they all have no effect or raise, as these functions are all guarantueed to succeed and can be served by a common base class.

    This covers the str.capitalize, str.upper, str.lower, str.swapcase, str.title, str.isalnum, str.isalpha, str.isdigit, str.islower, str.isupper, str.isspace, and str.istitle functions.

    For static optimization str.find and str.rfind were added, as they are e.g. used in a sys.version.find(...) style in the os module, helping to decide to not consider OS/2 only modules.

    Then, support for str.index and str.rindex was added, as these are very similar to str.find forms, only that these may raise an exception.

    Also add support for str.split and str.rsplit which will be used sometimes for code needed to be compile time computed, to e.g. detect imports.

    Same goes for endswith and startswith, the later is e.g. popular with sys.platform checks, and can remove a lot of code from compilation with them now being decided at compile time.


    A few str methods are still missing, with time we will achieve all of them, but this will take time.

  • Added trust for sys.builtin_module_names as well. The os module is using it to make platform determinations.

  • When writing constant values, esp. tuple, list, or dict values, an encoding of “last value” has been added, avoiding the need to repeat the same value again, making many values more compact.

  • When starting Nuitka, it usually restarts itself with information collected in a mode without the site module loaded, and with hash randomization disabled, for deterministic behaviour. There is a option to prevent this from happening, where the goal is to avoid it, e.g. in testing, say for the coverage taking, but that meant to parse the options twice, which also loads a lot of code.

    Now only a minimal amount of code is used, and the options are parsed only on the restart, and then an error is raised when it notices, it was not allowed to do so. This also makes code a lot cleaner.

  • Specialized comparison code for Python2 long and Python3 int code, making these operations much faster to use.

  • Specialized comparison code for Python2 unicode and Python3 str code, making these operations much faster to use, currently only == and != are fully accelerated, the other comparisons will follow.

  • Enable static libpython with Python3 Debian packages too. As with Python2, this will improve the performance of the created binary a lot and reduce size for standalone distribution.

  • Comparisons with in and not in also consider value traces and go through variables as well where possible. So far only the rich comparisons and is and is not did that.

  • Create fixed import nodes in re-formulations rather than __import__ nodes, avoiding later optimization doing that, and of course that’s simpler code too.

  • Python 3.10: Added support for union types as compiled time constants.

  • Modules are now fully optimized before considering which modules they are in turn using, this avoids temporary dependencies, that later turn out unused, and can shorten the compilation in some cases by a lot of time.

  • On platforms without a static link library, in LTO mode, and with gcc, we can use the -O3 mode, which doesn’t work for libpython, but that’s not used there. This also includes fake static libpython, as used by MinGW64 and Anaconda on Windows.

  • The anti-bloat plugin now also handles newer sklearn and knows more about the standard library, and its runners which it will exclude from compilation if use for it. Currently that is not the default, but it should become that.

  • Migrated the Nuitka blog from Nikola to Sphinx based ABlog and made the whole site render with Sphinx, making it a lot more usable.

  • Added a small presentation about Nuitka on the Download page, to make sure people are aware of core features.

  • The gi plugin is now always on. The copying of the typelib when gi is imported is harmless and people can disable the plugin if that’s not needed.

  • The matplotlib plugin is new and also always on. It previously was part of the numpy plugin, which is doing too many unrelated things. Moving this one out is part of a plan to split it up and have it on by default without causing issues.

  • MSYS2: Detecting MinGW and POSIX flavors of this Python. For the MinGW flavor of MSYS2, the option --mingw64 is now the default, before it could attempt to use MSVC, which is not going to work for it. And also the Tcl and Tk installations of it are being detected automatically for the tk-inter plugin.

  • Added Windows version to Nuitka version output, so we have this for bug reports.

  • User Manual: Added example explaining how to access values from your code in Nuitka project options.

  • UI: For Python flavors where we expect a static libpython, the error message will now point out how to achieve it for each flavor.

  • UI: Disable progress bar when --show-scons is used, it makes capturing the output from the terminal only harder.

  • UI: Catch error of specifying both --msvc= and --mingw64 options.

  • Distutils: Improved error messages when using setuptools or build integration and failing to provide packages to compile.

  • Plugins: Removed now unused feature to rename modules on import, as it was only making the code more complex, while being no more needed after recently adding a place for meta path based importers to be accounted for.

  • Twitter: Use embedded Tweet in Credits, and regular follow button in User Manual.

  • Warnings about imports not done, are now only given when optimization can not remove the usage, and no options relatved to following have been given.

  • Added Windows version to --version output of Nuitka. This is to more clearly recognize Windows 10 from Windows 11 report, and also the odd Windows 7 report, where tool chain will be different.

  • In Visual Code, the default Python used is now 3.9 in the “Linux” C configuration. This matches Debian Bullseye.

  • Nicer outputs from check mode of the autoformat as run for CI testing, displays problematic files more clearly.

  • Remove broken links to old bug tracker that is no longer online from the Changelog.

  • UI: When hitting CTRL-C during initial technical import detection, no longer ask to submit a bug report with the exception stack, instead exit cleanly.

  • Windows: Enable LTO mode for MinGW64 and other gcc by default. We require a version that can do it, so take advantage of that.

  • For cases, where code generation of a module takes long, make sure its name is output when CTRL-C is hit.

  • Windows: Splash screen only works with MSVC, added error indicator for MinGW64 that states that and asks for porting help.

  • Generate all existing C code for generic builtin type method calls automatically, and use those for method attribute lookups, making it easier to add more.

  • Changed TkInter module to data file providing interface, yielding the 2 directories in question, with a filter for demos.

  • The importing code got a major overhaul and no longer works with relative filenames, or filenames combined with package names, and module names, but always only with module names and absolute filenames. This cleans up some of the oldest and most complex code in Nuitka, that had grown to address various requirements discovered over time.

  • Major cleanup of Jinja2 template organisation

    Renamed all C templates from .j2 to .c.j2 for clarity, this was not done fully consistent before. Also move all C templates to nuitka.codegen package data, it will be confusing to make a difference between ones used during compile time and for the static generation, and the lines are going to become blurry.

    Added Jinja2 new macro CHECK_OBJECTS to avoid branches on argument count in the call code templates. More of these things should be added.

    Cleanup of code that generates header declarations, there was some duplication going on, that made it hard to generate consistent code.

  • Removed nuitka.finalizatios.FinalizationBase, we only have one final visitor that does everything, and that of course makes a lot of sense for its performance.

  • Major cleanup of the Scons C compiler configuration setup. Moved things to the dedicate function, and harmonized it more.

  • Resolved deprecation warnings given by with --python-debug for Nuitka.

  • Started test suite for Python PGO, not yet completely working though, it’s not yet doing what is needed though.

  • Added generated test that exercises str methods in multiple variations.

  • Revived reflected test suite, that had been removed, because of Nuitka special needs. This one is not yet passing again though, due to a few details not yet being as compatible as needed.

  • Added test suite for CPython 3.10 and enable execution of tests with this version on Github actions.


This release is another big step forward.

The amount of optimization added is again very large, some of which yet again unlocks more static optimization of module imports, that previously would have to be considered implicit. Now analysing these on the function level as well, we can start searching for cases, where it could be done, but is not done yet.

After starting with dict, method optimization has focused on str which is esp. important for static optimization of imports. The next goal will here be to cover list which are important for run time performance and currently not yet optimized. Future releases will progress there, and also add more types.

The C type specialization for Python3 has finally progressed, such that it is also covering the long and unicode and as such not limited to Python2 as much. The focus now needs to turn back to not working with PyObject * for these types, but e.g. with += 1 to make it directly work with CLONG rather than LONG for which structural changes in code generation will be needed.

For scalability, the anti-bloat work has not yet progressed as much as to be able to enable it by default. It needs to be more possible to disable it where it causes problems, e.g. when somebody really wants to include pytest and test frameworks generally, that’s something that needs to be doable. Compiling without anti-bloat plugin is something that is immediately noticeable in exploding module amounts. It is very urgently recommended to enable it for your compilations.

The support for Windows has been further refined, actually fixing a few important issues, esp. for the Qt bindings too.

This release adds support for 3.10 outside of very special match statements, bringing Nuitka back to where it works great with recent Python. Unfortunately orderedset is not available for it yet, which means it will be slower than 3.9 during compilation.

Overall, Nuitka is closing many open lines of action with this. The setuptools support has yet again improved and at this point should be very good.

Categories: FLOSS Project Planets

Test and Code: 175: Who Should Do QA?

Planet Python - Wed, 2022-01-12 03:00
  • Who should do QA?
  • How does that change with different projects and teams?
  • What does "doing QA" mean, anyway?

Answering these questions are the goals of this episode.

Sponsored By:

Support Test & Code in Python


<ul> <li>Who should do QA?</li> <li>How does that change with different projects and teams?</li> <li>What does &quot;doing QA&quot; mean, anyway?</li> </ul> <p>Answering these questions are the goals of this episode.</p><p>Sponsored By:</p><ul><li><a href="https://try.rollbar.com/testandcode/?utm_campaign=testandcode" rel="nofollow">Rollbar</a>: <a href="https://try.rollbar.com/testandcode/?utm_campaign=testandcode" rel="nofollow">Rollbar enables developers to proactively discover and resolve issues in their code, so they can work on continuous code improvement throughout the software development lifecycle. Learn more at [Rollbar.com](https://try.rollbar.com/testandcode/?utm_campaign=testandcode ) </a></li><li><a href="https://testandcode.com/pycharm" rel="nofollow">PyCharm Professional</a>: <a href="https://testandcode.com/pycharm" rel="nofollow">Try PyCharm Pro for 4 months and learn how PyCharm will save you time.</a> Promo Code: TESTANDCODE22</li></ul><p><a href="https://www.patreon.com/testpodcast" rel="payment">Support Test & Code in Python</a></p><p>Links:</p><ul><li><a href="https://www.thoughtworks.com/insights/blog/test-automation-who-should-be-involved" title="Test Automation - Who Should be Involved? | Thoughtworks" rel="nofollow">Test Automation - Who Should be Involved? | Thoughtworks</a></li></ul>
Categories: FLOSS Project Planets

Matt Glaman: hook_update_N or hook_post_update_NAME

Planet Drupal - Tue, 2022-01-11 23:10

Today I realized that I had no idea when it was appropriate to use hook_update_N or hook_post_update_NAME. I have ideas, but I was not sure about the concrete reasons. My gut instinct is that hook_update_N is for schema and other database-related changes. And, then, hook_post_update_NAME is for configuration changes and clearing caches once the schema changes have been finished.

But is that true? Does Drupal core follow this pattern? Finding examples in Drupal core was also tricky; I had to switch back to the 8.9.x branch to get a good collection of references.

Categories: FLOSS Project Planets

Specbee: How to Prepare for a Drupal 9 Migration - A Checklist

Planet Drupal - Tue, 2022-01-11 22:09
How to Prepare for a Drupal 9 Migration - A Checklist Shefali Shetty 12 Jan, 2022

As if you weren’t busy enough disinfecting your groceries when Drupal 9 was released in June 2020, you likely had a bit of a conundrum. Should I migrate to Drupal 9 now or just stick with Drupal 7 since I have until 2022?!. Should I move to Drupal 8 first and then make way to Drupal 9? Why should I even migrate to Drupal 9?!  

And why shouldn’t you ask those questions? Website migrations aren’t exactly what anyone looks forward to, but at some point it has to happen. Our best advice is just to dig your heels in and ask the question, “How do I prepare for Drupal 9 migration?”. 

If you’re asking that question right now, you’re well on your way to having a great migration experience! This checklist will give you an idea of the kind of information you must have ready before you begin the “Let’s Migrate!” discussion with your prospective Drupal development partner. And in case you’re still asking “Why” you should migrate to Drupal 9 - we have written extensively about that here, here and here. So let’s get down to business and dive straight into the things you should have ready before a Drupal 9 migration.


What’s New

Migrating to a new, more powerful and feature-packed CMS should be as exciting as moving to a new home. And new beginnings like these give you a chance to re-examine your current information architecture. Making these types of changes during migration is amazingly efficient use of developer time. Make a note if you believe there is a change in:

  • Purpose: Make a list of even the smallest changes in your business goals that could require you to add new features (or remove/edit existing ones).
  • Audience: Over time, if your target audience has changed or grown wider in scope, it’s probably time to accommodate them by changing your information architecture.
  • User Experience: Now, this can change depending on your audience, purpose, content, features and business goals. Revisit and analyze if you need a new design and user experience.
  • Content: Is your content being consumed by the right audience in the right way? Is it still relevant? Time to analyze your content and messaging.
  • Editorial Workflow: Had a recent change in your team structure or editorial workflow? Do you really need additional features or can it be handled by Drupal core features?
  • SEO Strategy: Been wanting to implement new SEO strategies but could not get them to work with your current architecture? This is a good time to make a note of all your new and improved SEO ideas.
Features and Functionalities

Change is Always Changing. As your business grows, the audience varies and goals broaden, you will need to make way for new features or edit existing ones. To be well prepared for your Drupal 9 migration, make sure you have a list and description of:

  • New features and functionality that you want to see in your new site
  • The changes you need to make to the existing functionalities
  • Critical features with description that need to remain unchanged
Audit Your Website

When we get approached for a Drupal migration project, our clients usually fall under two categories. Website managers who understand their system and information architecture well and those who are more content focused. For the latter, it is recommended to identify a reliable Drupal development partner to thoroughly assess your current architecture and suggest the best approach to migrate your website to Drupal 9.

If you know your Drupal website and its architecture well, you should:

  • Make sure you backup your current Drupal site. You don’t want to mess with the current data while you’re busy analyzing the website.
  • Create a content structure checklist. Analyze and list out the existing content types, taxonomy, views and blocks and other Drupal assets. 
  • List out all the Contributed and Custom modules that are currently being used/unused. You can go to admin/module/uninstall to find a list of all your enabled modules. With this information, your prospective Drupal development partner can then analyze if the modules have a straight upgrade path to Drupal 9 or they need to be rebuilt.
  • A description of the custom modules and the functionality that is achieved with these modules.
  • Make a checklist of user roles and examine the permissions given to them. List out any views associated with them.
  • If using a custom theme, you might need to share details on the theme structure with your development partner.

Now, if you don’t know that much about your Drupal website’s architecture and how it works, your potential Drupal development partner will (and should) conduct a migration audit. For the audit, you’ll need to share these details with the development team:

  • Admin access to the development or staging server. It’s best not to share the live server access details at very early stages. This will enable the team to obtain the list of modules, content types, taxonomies, blocks, views and more. With this list they can identify the best approach to upgrade your Drupal 7 site to Drupal 9.
  • A description or walkthrough of all the existing custom functionalities of the website.
  • A description of new features and functionalities you would like to add as part of the upgrade project.
  • If you need a revamped design and theme, have the description ready.
  Member Login

If you have a member’s area where non-admin website users login, it is recommended to create a user login (not admin) for the development partner. This login will help the Drupal team get a better understanding of the functionality of your site from a user’s perspective. Having said that, if your website allows free member logins, your development partner can create a login themselves without needing your assistance.

Planning for a migration is and will always remain the first and most crucial step before any of the points we discussed here in this article. The success of your migration significantly depends on how well (or badly) the Drupal migration has been planned. A Drupal 7 to 9 migration does not have to be complicated, especially when you choose the right Drupal development company with a perfect blend of Drupal expertise and project management. Looking for a development partner to audit your website for FREE? Fill out this quick form and our experts will get in touch with you soon.

Drupal Migration Drupal 9 Drupal 8 Drupal 7 Drupal Planet Drupal Development Subscribe to our Newsletter Now Subscribe Leave this field blank

Leave us a Comment

  Recent Blogs Image How to Prepare for a Drupal 9 Migration - A Checklist Image Performance Testing your website with Jmeter Image Exposing Your API in Drupal 9 - A Brief Tutorial Need help Migrating to Drupal 9? Schedule a call Featured Success Stories

A Drupal powered multi-site, multi-lingual platform to enable a unified user experience at SEMI.


Discover how our technology enabled UX Magazine to cater to their massive audience and launch outreach programs.


Discover how a Drupal powered internal portal encouraged the sellers at Flipkart to obtain the latest insights with respect to a particular domain.


Categories: FLOSS Project Planets

Plasma 5.24 Wallpaper: “Wavy McWallpaperface”

Planet KDE - Tue, 2022-01-11 19:20

After two tremendously fun livestreams the Plasma 5.24 wallpaper is all wrapped up. With this particular image we had a lot of fun using new techniques to create this wallpaper, and the entire process was a fun adventure. To download the wallpaper it’s available on OpenDesktop and GetHowNewStuff if you’re a Plasma user.

The wallpaper was first sketched in the Krita painting application. Up until this point wallpapers I authored used a fairly inflexible technique of creating a polygon grid and manipulating it, but this new shape would require new techniques.

In Inkscape a wireframe was drawn using the line tool. This was done by drawing curved lines roughly matched over the sketch, applying successive wireframes one over another until we could rely on the snapping tools in Inkscape to place polygons.

This ultimately resulted in 2,221 hand-drawn polygons, layered in a way similar to reptile scales so gaps would not show through once fills were applied. People often question if these are done in Blender, but Inkscape is actually the software of the day with this being done entirely in 2D.

Fills were applied as linear gradients to the grouped polygons. At this point edges were also drawn in and I was getting ready to use the “Jitter Gradients” plugin I developed some years ago for the purpose of differentiating the individual polygons, but alas it wasn’t compatible with modern Inkscape! AAAAGH!

While I was busy having a panic attack live on-air Niccolò Veggero swept in and graciously updated the script to be compatible while I worked in other areas. What a lifesaver! With the Jitter Gradients plugin fixed up work began hopping between Krita and Inkscape, colours starting roughly landing, and we quickly approached the end of the wallpaper work.

Layers layers layers ahoy! This was the state of the wallpaper at the end of the second livestream. While almost everything was in place, in practise it’s never a bad idea to walk away for a few hours to come back later with clear eyes.

After coming back to the image several adjustments were made. A lot of the work I had done in Krita during the livestream was replaced, mostly because I realized I didn’t do the work in 8K, which we offer now. There was also a few steps in GIMP such as noise and some minor light-curve editing.

And so ended the work on the Plasma 5.24 wallpaper! After taking it up with the chat on the livestream it was quickly decided to be named “Wavy McWallpaperface”. The last steps are pretty standard; we run it through our cropping and sizing script which produces the highest quality versions for a variety of resolutions. If you noticed that the base image is slightly taller than “standard” it’s because it was, to accommodate cropping so it’s not just removing content for taller aspect ratios. The cropping script was also adjusted slightly for this wallpaper so it wouldn’t crop the top, which is the more interesting bit.

If you’re a crazy person and you wish to watch the wallpaper being created you can watch the process as it was streamed on Youtube:
Part 1: Wireframe & Polygon Creation
Part 2: Everything Else

To download the wallpaper once again it’s available on OpenDesktop at various resolutions, including the mobile version!

Categories: FLOSS Project Planets

Read the Docs: Read the Docs newsletter - January 2022

Planet Python - Tue, 2022-01-11 19:00

Welcome to the latest edition of our monthly newsletter, where we share the most relevant updates around Read the Docs, offer a summary of new features we shipped during the previous month, and share what we’ll be focusing on in the near future.

Company highlights
  • We are now managing custom domains for our corporate users using Cloudflare SSL for SaaS, which will remove the manual work that was needed on our side and make the process of setting up a custom domain almost instantaneous. It also will allow us to offer a CDN much easier in the future.
  • We improved our spam classification system, and started blocking the dashboard on spammy projects. We are happy to report that the traffic to spammy projects has already reduced significantly.
New features

December and January have been slow months, and we mainly worked on internal changes and documentation improvements. Among the major user-facing changes:

Thanks to our external contributor Çağatay Yiğit Şahin.

You can always see the latest changes to our platforms in our Read the Docs Changelog.

Upcoming features
  • Ana will continue working on the new landing pages, polishing the copywriting along with Juan Luis and translating the mockups to Pelican templates.
  • Anthony will continue working on frontend scaffolding and finance bits.
  • Eric will continue to focus on business and sales efforts, and performing code review.
  • Juan Luis will work with Ana in the new landing pages, and with Manuel in a new process to migrate users from legacy or deprecated configurations.
  • Manuel will wrap up the migration to Django 3, improve the queryability of the project configuration in our database, and refactor our task queue to improve its robustness.
  • Santos will add support for multiple .readthedocs.yaml files per repository.
Possible issues

The Python packaging ecosystem is evolving rapidly to accomodate for modern standards that will make our life easier, and in particular setuptools has been introducing some breaking changes in recent times. We anticipated this sort of breakage for our users so we pinned the setuptools version in late November. However, a small number of projects did not have this version cap active because of a bug on our side and experienced failing builds after a new setuptools release. We quickly fixed the problem and offered a range of possible solutions to affected projects.

Considering using Read the Docs for your next Sphinx or MkDocs project? Check out our documentation to get started!

Categories: FLOSS Project Planets

GNU Guix: Announcing the second online Guix Days

GNU Planet! - Tue, 2022-01-11 19:00

The Guix hackers are very happy to announce the second online Guix Days Conference on 19 & 20 February 2022. This conference is open to everyone and will be held entirely online. Want to speak? Submit your proposal!

Important dates:

  1. February 8: Deadline for talks proposal.
  2. February 12: Deadline for releasing your pre-recorded talks.
  3. February 14: Release of the schedule.
  4. February 19: Conference day!
  5. February 20: Conference day!

The agenda of these two days is:

  • pre-recorded talks with live question and answer sessions
  • birds of a feather (BoF) sessions
  • lightning round talks, if possible
  • retrospective and future of Guix
  • hack together

Talks will be released before the conference day, watch them as soon as possible! And: no registration fee.

Until February 8: talk proposals

Propose your talks by sending them to guix-days@gnu.org. Feel free to drop in #guix on irc.libera.chat to discuss what you would like to talk about before submitting. :)

You can choose one of the following formats:

  • Standard talk. 15-45 minutes pre-recorded presentation and a 5 minutes lightning talk. The 5-minute presentation will be live, to refresh our minds, followed by a 30 minutes live Q&A.
  • BoF (birds of a feather, for a session with a small group who wants to talk about a specific topic) with no presentation. You may prepare something live to spark conversations.
  • Lightning talk with a 5 minutes live presentation

In addition to the format you would like to choose, please describe your session with 10 lines or more (for lightning talks, at least 1 sentence).

Once you have sent your proposal, you will be notified in the following days whether your talk will be part of the Guix Days. Submit earlier to get more time to prepare your session!

Even for live presentation, please prepare a back-up pre-recorded talk, so we can play it if you cannot attend or have a technical problem during the Guix days. The deadline for short presentations (5 minutes) is February 16.

We welcome all kinds of topics from the community, especially your own experience with Guix, your cool projects that involve Guix in some way, infrastructure around guix (translations, continuous integration, ...), and any subject you feel should be discussed during the conference.

We particularly encourage people who consider themselves part of a group underrepresented in Guix and the broader free software movement to submit a talk. Do not hesitate to get in touch with the organizers at guix-days@gnu.org if unsure or if you would like guidance on how to prepare your talk.

Please make sure your talk is accessible to a non-expert audience, for instance by explaining the general context before diving into technical descriptions, and by avoiding acronyms and jargon.

We accept talks in languages other than English provided English subtitles are included.

Have a look at the topics from the last conference for ideas, but don't hesitate to innovate in your proposals!

February 8 (or before) – 12: prepare your session

The aim of the pre-recorded talks is to demonstrate new features, what you are hacking on, introduce the subject for easing the live question and answer sessions or BoFs. These pre-recorded talks should be 15–45 minutes long. Feel free to ask if you need help with the recording.

You are free to choose whichever storage platform you want (e.g., your own website, a PeerTube instance, a Nextcloud instance, etc.), but we will need to have access to the original file so we can publish it later on audio-video.gnu.org. Your video must be released under a license that at least allows anyone to copy and share it, for any purpose.

You will have to release the video publicly before February 12, so everyone has a chance to see it before the conference. If you are not able to do so (for instance your server cannot handle a huge load), you can alternatively send us a private link to the video and we will upload it on audio-video.gnu.org. If you decide to do so, you will need to have the video ready by February 10.

February 12–18: watch the talks

But don't miss the Fosdem conference either!

Be sure to watch the pre-recorded talks before the conference. There will be no presentations on the 19 nor 20.

February 19–20: participate

Coming soon! Stay tuned.

Code of Conduct

This online conference is an official Guix event. Therefore, the Code of Conduct applies. Please be sure to read it beforehand!

About GNU Guix

GNU Guix is a transactional package manager and an advanced distribution of the GNU system that respects user freedom. Guix can be used on top of any system running the Hurd or the Linux kernel, or it can be used as a standalone operating system distribution for i686, x86_64, ARMv7, and AArch64 machines.

In addition to standard package management features, Guix supports transactional upgrades and roll-backs, unprivileged package management, per-user profiles, and garbage collection. When used as a standalone GNU/Linux distribution, Guix offers a declarative, stateless approach to operating system configuration management. Guix is highly customizable and hackable through Guile programming interfaces and extensions to the Scheme language.

Categories: FLOSS Project Planets

TestDriven.io: Introduction to Django Channels

Planet Python - Tue, 2022-01-11 17:28
This tutorial shows how to use Django Channels to create a real-time application.
Categories: FLOSS Project Planets

hello @ Savannah: hello-2.11 released [stable]

GNU Planet! - Tue, 2022-01-11 15:04

I’m delighted to announce a new release of GNU hello.  This version has many minor fixes and improvements made in the last eight years.

  • Noteworthy changes in release 2.11 (2022-01-05) [stable]

Remove -h and -v short options.

Various code tidying, including avoiding forward declarations, removing dead code, new test for multibyte strings, better use of gnulib, update to more recent gnulib and add git hooks from coreutils.

Categories: FLOSS Project Planets

PyCoder’s Weekly: Issue #507 (Jan. 11, 2022)

Planet Python - Tue, 2022-01-11 14:30

#507 – JANUARY 11, 2022
View in Browser »

Hey there,

Quick announcement: I’m looking to hire a talented PyCoder’s Weekly Curator and Podcast Co-Host to join the PyCoder’s team in a part-time, freelance role 🎉

In this role, you’ll research and curate links and news for PyCoder’s Weekly and you’ll regularly join the Real Python Podcast to co-host the show with Christopher Bailey to talk about the latest Python news and projects.

You’ll work closely with me (Dan Bader) and the host of the RP Podcast (Christopher Bailey) in this role and we will train you on the specifics of our curation tools and podcast recording process.

Basically, you’ll be getting paid to read Python articles and stay up to date with the latest projects and Python news 🎓🐍

If you’re interested or know anybody who would be a great fit for this role, check out the full job posting at the link below:

→ PyCoder’s Curator and Podcast Co-Host (Part-Time, Remote) Wanted

Build a Django Front End With Bulma – Part 2

In the second part of this tutorial series, you’ll continue to build out a social network with Django. You’ll learn how to set up routing, views, and templates for your app. You’ll also apply CSS styling to the Django front end by using the Bulma framework to improve your app’s user interface.

Deploy Your Python Script on the Web With Flask

In this course, you’ll learn how to go from a local Python script to a fully deployed Flask web application that you can share with the world.

How to Quickly Label Data for Machine Learning

With Toloka, you can control the accuracy and speed of data labeling to develop high performing ML models. Our platform supports annotation for image classification, semantic segmentation, object detection, named entity recognition, sentiment analysis, speech recognition, text classification →
TOLOKA AI sponsor

Unravelling from for raise Statements


Django Security Releases Issued: 4.0.1, 3.2.11, and 2.2.26


Announcing PSF Fellow Members for Q4 2021


Discussions I Found a One-Char Typo in the Docs for Python’s Typing_extensions Library

Related discussion on Hacker News.

Python Is “Language of the Year for 2021” According to TIOBE


Python Jobs PyCoder's Weekly Curator and Podcast Co-Host (Part-Time, Remote)

Real Python

Python Engineer Web Scraping (Asia, TX, America)


Senior Software Engineer (Anywhere)


Sr DevOps Engineer (San Jose, CA, USA)

Tara Techincal Solutions

Senior Software Engineer (Anywhere)


More Python Jobs >>>

Articles & Tutorials Dependency Risk and Funding

From the creator of Flask: “I have a love/hate relationship with dependencies. I wrote about this extensively on this blog. […] Somehow very unsurprisingly nothing has actually improved in that regard in the last 5 years. In fact, I think the problem has become significantly worse. Where a few years back the main fear here was high profile developers being targeted, the dependency discussion is now overlapped and conflated with discussions about funding and sustainability.”

Continuing to Unravel Python’s Syntactic Sugar With Brett Cannon

“A year ago, we had Brett Cannon on the show to discuss his blog series about unravelling Python’s syntactic sugar. Brett has written 15 more entries in the series, and he returns to the show this week to continue our conversation. We dive into unravelling async and await statements and their relationship with Python’s generators.”

Do You Know if Your Users Toggled Off Notifications

Clubhouse case study: you’ll remember they were the most downloaded app in APR of 2021. If you recall they spammed users with notifications. Most were irrelevant. Had they had a centralized notification system with a sophisticated preferences module the mass exodus likely could have been avoided →
COURIER sponsor

3 Things You Might Not Know About Numbers in Python

If you’ve done any coding in Python, there’s a good chance that you’ve used a number in one of your programs. But there’s more to numbers then just their raw value. Take a deep dive into numbers in Python and explore three things about them that you might not know about.
DAVID AMOS • Shared by David Amos

Build and Handle POST Requests in Django – Part 3

In the third part of this tutorial series, you’ll continue to build out a social network with Django. You’ll make it possible to follow and unfollow user profiles, create buttons to handle POST requests, and set up Django models for your users’ text-based content.

5% of 666 Python Repos Had Comma Typos (Including Tensorflow, and PyTorch, Sentry, and V8)

Related discussion on Hacker News.

Start the New Year Working Towards Your New Career in Data Analytics

Ready to take the leap and start working towards your career in data analytics? With Springboard’s Data Analytics Bootcamp, you’ll gain the skills, experience, and build a professional portfolio needed to get hired. Learn more today.

Nine Rules for Writing Python Extensions in Rust

Practical lessons from upgrading Bed-Reader, a Python bioinformatics package.

Neural Network From Scratch

Learn how a neural network works by building one from scratch, with Python.

Projects & Code hvPlot: High-Level Plotting API


Yamale: A Schema and Validator for YAML


kent: Fake Sentry Server for Local Development, Debugging, and Integration Testing


stories: Service Objects Designed With OOP in Mind


pystitcher: Stitch Your PDF Files Together Using a Declarative Markdown File as Input


terrain-erosion-3-ways: Generating Terrain With Erosion Features


Events Weekly Real Python Office Hours Q&A (Virtual)

January 12, 2021


January 13, 2022

Python Atlanta

January 13, 2022

Global AI Bootcamp 2022

January 15 to January 16, 2022


January 15, 2022

PyDelhi User Group Meetup

January 15, 2022

Python Pizza Holguín

January 15, 2022

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

[ 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 ]

Categories: FLOSS Project Planets

Latte Dock v0.10.7 | Bug Fix Release

Planet KDE - Tue, 2022-01-11 09:55


Let's welcome Latte Dock v0.10.7 the 7th Official Bug Fix Release of v0.10.x branch!   Go get it from, download.kde.org*


  • multi-screen: always trust KWin under X11 in order to set correct struts for panels and docks
  • automatically offset centered applets when the left or right widgets overlap the centered one
  • windowsgobelow: show properly during startup
  • kwinedges: calculate accurately their size and position
  • improve applets dragging during rearrange and configure widgets mode
  • hide thin tooltips properly at some cases that were stack
  • fill one pixel gap of justify splitters during rearrange and configure widgets mode
  • fix, windows belong to screen whenever they are touching it. This way a window could belong in more than one screens and be taken into account for visibility modes and active window tracking
  • remove file extensions for layouts and templates properly in order to identify the layout or template name
  • fix build for Freebsd
  • x11: force OnAllDesktops for all docks and panels during creation
  • fix empty availableScreenRegion broadcast to Plasma


You can ping me at https://www.reddit.com/user/psifidotos in order to give you my paypal account.
or you can split your donation between my active projects in kde store. -----   * archive has been signed with gpg key: 325E 97C3 2E60 1F5D 4EAD CF3A 5599 9050 A2D9 110E


Categories: FLOSS Project Planets

Python for Beginners: Check For Prime Number in Python

Planet Python - Tue, 2022-01-11 09:23

Prime numbers are those numbers that have only two factors i.e. 1 and the number itself. In this article, we will discuss two ways to check for a prime number in python.

What is a prime number?

Prime numbers are those positive integers greater than one that has only two factors. The examples of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc.


  • 2 has only two factors i.e. 1 and 2.
  • 3 has only two factors i.e. 1 and 3.
  • 5 has only two factors i.e. 1 and 5.

You can observe that all other numbers also have only two factors. 

Check For Prime Number in Python

For checking if a number is prime or not, we just have to make sure that all the numbers greater than 1 and less than the number itself should not be a factor of the number. For this, we will define a function isPrime() that takes a number N as input. Then it checks whether any number between 2 and N-1 is a factor of N or not using a for loop. If a factor is present, it returns False stating that the input number N is not a prime number. Otherwise, it returns True.

def isPrime(N): for number in range(2, N): if N % number == 0: return False return True input_number = 23 output = isPrime(input_number) print("{} is a Prime number:{}".format(input_number, output)) input_number = 126 output = isPrime(input_number) print("{} is a Prime number:{}".format(input_number, output))


23 is a Prime number:True 126 is a Prime number:False

In the above example, we have checked every number from 2 to N-1 to see if it is a factor of N or not. We can optimize this process by checking numbers till N/2 instead of N-1. This is so because the only factor of N greater than N/2 is the number N itself. So, we will check for factors in numbers only till N/2. Additionally, we can also check if a number is even or not. If a number greater than 2 is even, it will never be a prime number. We can define an improved isPrime() function using these concepts as given below.

def isPrime(N): for number in range(2, N//2): if N % number == 0: return False return True input_number = 23 output = isPrime(input_number) print("{} is a Prime number:{}".format(input_number, output)) input_number = 126 output = isPrime(input_number) print("{} is a Prime number:{}".format(input_number, output))


23 is a Prime number:True 126 is a Prime number:False

We can again optimize the above program using simple logic. You can observe that factors of a number always occur in pairs. For a number N, the factors can be paired as (1, N), (2, N/2), (3, N/3), (4, N/4) till (N1/2, N1/2). So, for checking for factors, we can check only till N1/2 instead of N/2. 

For example, if we are given a number 100, all the factors can be paired as (1,100), (2,50),(4,25), (5,20), and (10,10). Here, if 100 is divisible by 2, it must be divisible by 50, if 100 is divisible by 4, it must be divisible by 25. We don’t need to explicitly check both the numbers in a pair to check if a number is a factor or not. So, To check for prime number, We can simply check for a factor till N1/2 instead of N/2 using a while loop. If a factor is not present between 2 and N1/2, the number must be a prime number. Using this logic, we can modify the isPrime() function used in the above example as follows.

def isPrime(N): count = 2 while count ** 2 <= N: if N % count == 0: return False count = count + 1 return True input_number = 23 output = isPrime(input_number) print("{} is a Prime number:{}".format(input_number, output)) input_number = 126 output = isPrime(input_number) print("{} is a Prime number:{}".format(input_number, output))


23 is a Prime number:True 126 is a Prime number:False Conclusion

In this article, we have discussed three ways to check for a prime number in python. To learn more about numbers, you can read this article on complex numbers in python. You might also like this article on decimal numbers in Python.

The post Check For Prime Number in Python appeared first on PythonForBeginners.com.

Categories: FLOSS Project Planets

Ritesh Raj Sarraf: ThinkPad AMD Debian

Planet Debian - Tue, 2022-01-11 09:07

After a hiatus of 6 years, it was nice to be back with the ThinkPad. This blog post briefly touches upon my impressions with the current generation ThinkPad T14 Gen2 AMD variant.

ThinkPad T14 Gen2 AMD Lenovo

It took 8 weeks to get my hands on the machine. Given the pandemic, restrictions and uncertainities, not sure if I should call it an ontime delivery. This was a CTO - Customise-to-order; so was nice to get rid of things I really didn’t care/use much. On the other side, it also meant I could save on some power. It also came comparatively cheaper overall.

  • No fingerprint reader
  • No Touch screen

There’s still parts where Lenovo could improve. Or less frustate a customer. I don’t understand why a company would provide a full customization option on their portal, while at the same time, not provide an explicit option to choose the make/model of the hardware one wants. Lenovo deliberately chooses to not show/specify which WiFi adapter one could choose. So, as I suspected, I ended up with a MEDIATEK Corp. Device 7961 wifi adapter.


For the first time in my computing life, I’m now using AMD at the core. I was pretty frustrated with annoying Intel Graphics bugs, so decided to take the plunge and give AMD/ATI a shot, knowing that the radeon driver does have decent support. So far, on the graphics side of things, I’m glad that things look bright. The stock in-kernel radeon driver has been working perfect for my needs and I haven’t had to tinker even once so far, in my 30 days of use.

On the overall system performance, I have not done any benchmarks nor do I want to do. But wholly, the system performance is smooth.


This is where things need more improvement on the AMD side. This AMD laptop terribly draws a lot of power in suspend mode. And it isn’t just this machine, but also the previous T14 Gen1 which has similar problems. I’m not sure if this is a generic ThinkPad problem, or an AMD specific problem. But coming from the Dell XPS 13 9370 Intel, this does draw a lot lot more power. So much, that I chose to use hibernation instead.

Similarly, on the thermal side, this machine doesn’t cool down well as compared the the Dell XPS Intel one. On an idle machine, its temperature are comparatively higher. Looking at powertop reports, it does show to consume an average of 10 watts power even while idle.

I’m hoping these are Linux ingeration issues and that Lenovo/AMD will improve things in the coming months. But given the user feedback on the ThinkPad T14 Gen1 thread, it may just be wishful thinking.


The overall hardware support has been surprisingly decent. The MediaTek WiFi driver had some glitches but with Linux 5.15+, things have considerably improved. And I hope the trend will continue with forthcoming Linux releases. My previous device driver experience with MediaTek wasn’t good but I took the plunge, considering that in the worst scenario I’d have the option to swap the card.

There’s a lot of marketing about Linux + Intel. But I took a jibe with Linux + AMD. There are glitches but nothing so far that has been a dealbreaker. If anything, I wish Lenovo/AMD would seriously work on the power/thermal issues.


Other than what’s mentioned above, I haven’t had any serious issues. I may have had some rare occassional hangs but they’ve been so infrequent that I haven’t spent time to investigate those.

Upon receiving the machine, my biggest requirement was how to switch my current workstation from Dell XPS to Lenovo ThinkPad. I’ve been using btrfs for some time now. And over the years, built my own practise on how to structure it. Things like, provisioning [sub]volumes, based on use cases is one thing I see. Like keeping separate subvols for: cache/temporary data, copy-on-write data , swap etc. I wish these things could be simplified; either on the btrfs tooling side or some different tool on top of it.

Below is filtered list of subvols created over years, that were worthy of moving to the new machine.

rrs@priyasi:~$ cat btrfs-volume-layout ID 550 gen 19166 top level 5 path home/foo/.cache ID 552 gen 1522688 top level 5 path home/rrs ID 553 gen 1522688 top level 552 path home/rrs/.cache ID 555 gen 1426323 top level 552 path home/rrs/rrs-home/Libvirt-Images ID 618 gen 1522672 top level 5 path var/spool/news ID 634 gen 1522670 top level 5 path var/tmp ID 635 gen 1522688 top level 5 path var/log ID 639 gen 1522226 top level 5 path var/cache ID 992 gen 1522670 top level 5 path disk-tmp ID 1018 gen 1522688 top level 552 path home/rrs/NoBackup ID 1196 gen 1522671 top level 5 path etc ID 23721 gen 775692 top level 5 path swap 18:54 ♒ ॐ ♅ ♄ ⛢ ☺ 😄 btrfs send/receive

This did come in handy but I sorely missed some feature. Maybe they aren’t there, or are there and I didn’t look close enough. Over the years, different attributes were set to different subvols. Over time I forget what feature was added where. But from a migration point of view, it’d be nice to say, “Take this volume and take it with all its attributes”. I didn’t find that functionality in send/receive.

There’s get/set-property which I noticed later but by then it was late. So some sort of tooling, ideally something like btrfs migrate or somesuch would be nicer.

In the file system world, we already have nice tools to take care of similar scenarios. Like with rsync, I can request it to carry all file attributes.

Also, iirc, send/receive works only on ro volumes. So there’s more work one needs to do in:

  1. create ro vol
  2. send
  3. receive
  4. don’t forget to set rw property
  5. And then somehow find out other properties set on each individual subvols and [re]apply the same on the destination

I wish this all be condensed into a sub-command.

For my own sake, for this migration, the steps used were:

user@debian:~$ for volume in `sudo btrfs sub list /media/user/TOSHIBA/Migrate/ | cut -d ' ' -f9 | grep -v ROOTVOL | grep -v etc | grep -v btrbk`; do echo $volume; sud o btrfs send /media/user/TOSHIBA/$volume | sudo btrfs receive /media/user/BTRFSROOT/ ; done Migrate/snapshot_disk-tmp At subvol /media/user/TOSHIBA/Migrate/snapshot_disk-tmp At subvol snapshot_disk-tmp Migrate/snapshot-home_foo_.cache At subvol /media/user/TOSHIBA/Migrate/snapshot-home_foo_.cache At subvol snapshot-home_foo_.cache Migrate/snapshot-home_rrs At subvol /media/user/TOSHIBA/Migrate/snapshot-home_rrs At subvol snapshot-home_rrs Migrate/snapshot-home_rrs_.cache At subvol /media/user/TOSHIBA/Migrate/snapshot-home_rrs_.cache At subvol snapshot-home_rrs_.cache ERROR: crc32 mismatch in command Migrate/snapshot-home_rrs_rrs-home_Libvirt-Images At subvol /media/user/TOSHIBA/Migrate/snapshot-home_rrs_rrs-home_Libvirt-Images At subvol snapshot-home_rrs_rrs-home_Libvirt-Images ERROR: crc32 mismatch in command Migrate/snapshot-var_spool_news At subvol /media/user/TOSHIBA/Migrate/snapshot-var_spool_news At subvol snapshot-var_spool_news Migrate/snapshot-var_lib_machines At subvol /media/user/TOSHIBA/Migrate/snapshot-var_lib_machines At subvol snapshot-var_lib_machines Migrate/snapshot-var_lib_machines_DebianSidTemplate ..... snipped .....

And then, follow-up with:

user@debian:~$ for volume in `sudo btrfs sub list /media/user/BTRFSROOT/ | cut -d ' ' -f9`; do echo $volume; sudo btrfs property set -ts /media/user/BTRFSROOT/$volume ro false; done ROOTVOL ERROR: Could not open: No such file or directory etc snapshot_disk-tmp snapshot-home_foo_.cache snapshot-home_rrs snapshot-var_spool_news snapshot-var_lib_machines snapshot-var_lib_machines_DebianSidTemplate snapshot-var_lib_machines_DebSidArmhf snapshot-var_lib_machines_DebianJessieTemplate snapshot-var_tmp snapshot-var_log snapshot-var_cache snapshot-disk-tmp

And then finally, renaming everything to match proper:

user@debian:/media/user/BTRFSROOT$ for x in snapshot*; do vol=$(echo $x | cut -d '-' -f2 | sed -e "s|_|/|g"); echo $x $vol; sudo mv $x $vol; done snapshot-var_lib_machines var/lib/machines snapshot-var_lib_machines_Apertisv2020ospackTargetARMHF var/lib/machines/Apertisv2020ospackTargetARMHF snapshot-var_lib_machines_Apertisv2021ospackTargetARM64 var/lib/machines/Apertisv2021ospackTargetARM64 snapshot-var_lib_machines_Apertisv2022dev3ospackTargetARMHF var/lib/machines/Apertisv2022dev3ospackTargetARMHF snapshot-var_lib_machines_BusterArm64 var/lib/machines/BusterArm64 snapshot-var_lib_machines_DebianBusterTemplate var/lib/machines/DebianBusterTemplate snapshot-var_lib_machines_DebianJessieTemplate var/lib/machines/DebianJessieTemplate snapshot-var_lib_machines_DebianSidTemplate var/lib/machines/DebianSidTemplate snapshot-var_lib_machines_DebianSidTemplate_var_lib_portables var/lib/machines/DebianSidTemplate/var/lib/portables snapshot-var_lib_machines_DebSidArm64 var/lib/machines/DebSidArm64 snapshot-var_lib_machines_DebSidArmhf var/lib/machines/DebSidArmhf snapshot-var_lib_machines_DebSidMips var/lib/machines/DebSidMips snapshot-var_lib_machines_JenkinsApertis var/lib/machines/JenkinsApertis snapshot-var_lib_machines_v2019 var/lib/machines/v2019 snapshot-var_lib_machines_v2019LinuxSupport var/lib/machines/v2019LinuxSupport snapshot-var_lib_machines_v2020 var/lib/machines/v2020 snapshot-var_lib_machines_v2021dev3Slim var/lib/machines/v2021dev3Slim snapshot-var_lib_machines_v2021dev3SlimTarget var/lib/machines/v2021dev3SlimTarget snapshot-var_lib_machines_v2022dev2OspackMinimal var/lib/machines/v2022dev2OspackMinimal snapshot-var_lib_portables var/lib/portables snapshot-var_log var/log snapshot-var_spool_news var/spool/news snapshot-var_tmp var/tmp snapper

Entirely independent of this, but indirectly related. I use snapper as my snapshotting tool. It worked perfect on my previous machine. While everything got migrated, the only thing that fell apart was snapper. It just wouldn’t start/run proper. Funny thing is that I just removed the snapper configs and reinitialized with the exact same config again, and voila snapper was happy.


That was pretty much it. With the above and then also migrating /boot and then just chroot to install the boot loader. At some time, I’d like to explore other boot options but given that that is such a non-essential task, it is low on the list.

The good part was that I booted into my new machine with my exact workstation setup as it was. All the way to the user cache and the desktop session. So it was nice on that part.

But I surely think there’s room for a better migration experience here. If not directly as btrfs migrate, then maybe as an independent tool. The problem is that such a tool is going to be used once in years, so I didn’t find the motivation to write one. But this surely would be a good use case for the distribution vendors.

Categories: FLOSS Project Planets

Real Python: Working With Pipenv

Planet Python - Tue, 2022-01-11 09:00

Managing multiple Python projects with their own third-party packages can get complicated. It is best practice to use a virtual environment to sandbox the requirements for each of your projects. Enter pipenv, the official recommended package management tool for Python. It handles both installation and virtual environments to help you manage your Python dependencies.

In this course, you’ll learn about:

  • How to use pip to install a package
  • Where Python puts packages by default
  • How to use pipenv to create virtual environments and install packages
  • How pipenv handles package conflicts

[ 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 ]

Categories: FLOSS Project Planets

Sumana Harihareswara - Cogito, Ergo Sumana: Some Novel Python Packaging/Distribution/Inspection/Installation Projects

Planet Python - Tue, 2022-01-11 05:40
Some Novel Python Packaging/Distribution/Inspection/Installation Projects
Categories: FLOSS Project Planets

Agiledrop.com Blog: Marketing accessibility – 10 known and less known tips and tricks

Planet Drupal - Tue, 2022-01-11 05:21

In this article, we break down 10 known and less known accessibility tips and tricks focused on marketers.

Categories: FLOSS Project Planets