PyCharm

Last update: April 25, 2021 10:40 AM UTC

April 24, 2021


Weekly Python StackOverflow Report

(cclxxii) stackoverflow python report

These are the ten most rated questions at Stack Overflow last week.
Between brackets: [question score / answers count]
Build date: 2021-04-24 19:06:09 GMT


  1. Why is a=a*100 scrutinizingly two times faster than a*=100? – [16/2]
  2. Django – return each model value without field – [8/1]
  3. How to compile Python Electron JS into desktop app (exe) – [7/1]
  4. How to load a pre-trained PyTorch model? – [7/1]
  5. Robot return to origin – [6/3]
  6. Create and solve variegated combinations of linear equation systems using data stored in several matrices in python – [6/1]
  7. How to build a Tensorflow model with increasingly than one input? – [6/1]
  8. Dynamically getting a list of standard library python packages names – [6/1]
  9. how to get a subgroup start finish indexes of dataframe – [5/4]
  10. Faster way to sum all combinations of rows in dataframe – [5/3]

April 24, 2021 07:07 PM UTC


Lucas Cimon

Undying Sunset : a PDF video game

UNDYING DUSK

Undying Dusk is a video game in a PDF format,
with a gameplay based on exploration and logic puzzles,
in the tradition of dungeon crawlers.

A expletive set by the Empress keeps the world in an eternal dusk.
You are have recently found shelter in an eerie monastery.

GIF trailer [#1](https://chezsoi.org/shaarli/?addtag=1)

Featuring:

— Permalink

April 24, 2021 04:50 PM UTC


Python Pool

6 Examples to Demystify Python locals() Function

Introduction

In python, we have discussed many concepts and conversions. But sometimes, we come to a situation where we need to return the wordlist equal to the current local symbol table. In this tutorial, we will be discussing the concept of the python locals() function, which is used to updates and returns a wordlist of the current local symbol table.

What is locals() function in Python?

Python locals() function is an in-built function used to update and return a wordlist of the current local symbol table. It is mostly used for debugging purposes. With the help of this function, We can trammels what variables are present in the local telescopic and their values. The local telescopic is within the function, within the class, etc.

Symbol Table: A symbol table is a type of data structure maintained or created by a compiler used to store all necessary information well-nigh the program. These include all the variable names, methods, classes, etc.

Local Symbol Table: The table is used to store all the information needed to the local telescopic of the program, and this information can be accessed using the seated function locals().

Syntax

locals()

Parameters

It does not take any parameter.

Return value

It returns the wordlist associated with the current local symbol table.

Examples of locals() function in Python

Here, we will be discussing all the examples of the built in locals() function in python:

1. Using locals() function in Python

In this example, we will try to print directly the locals() function with the help of the print function in python. locals() function will directly paste the Local Symbol Table information on the console, on that telescopic where locals() was tabbed from! Let us squint at the example for understanding the concept in detail.

#print() function and locals() function
print(locals())

Output:

Using locals() function in Python

Explanation:

  • Here, we will directly print the given function with the help of the print function.
  • locals() function will directly paste the Local Symbol Table information on the console, on that telescopic where locals() was tabbed from!
  • Hence, we obtain the required dictionary.

2. Using Python locals() function inside local scope

In this example, we will be using the function inside the local telescopic of the program. In this, we will be creating the two functions and then undeniability the locals() function. Let us squint at the example for understanding the concept in detail.

def NotPresent():
    return locals()

def present():
    Present = True
    return locals()

print('NotPresent of locals:', NotPresent())
print('Present of locals:', present())

Output:

locals() function inside local scope

Explanation:

  • Firstly, we will make two functions i.e NotPresent() and present().
  • Inside, the Notpresent() function we will directly return the values of locals() function.
  • Inside, the present() function we will put present equals to True and return locals() function.
  • Hence, we will see the output of both the function made.

3. Updating wordlist values by Python locals() Function

In this example, we will be updating locals() wordlist values. Let us squint at the example for understanding the concept in detail.

def localsPre():
    str = True
    print(str)
    locals()['str'] = False;
    print(str)

localsPre()

Output:

Updating wordlist values

Explanation:

  • Firstly, we will make the localsPre() function in the code.
  • Then, we will pinpoint that function with str equals to True and print the value of str.
  • After that, we will try to update locals() wordlist values by putting str equals to False.
  • At last, we will see the output.
  • Hence, you can see the output.

4. Python locals() function for global environment

In this example, we will be printing both the locals() function and theglobals() function. Through this, we will be telling you that the local symbol table is the same as the global symbol table in the specimen of the global environment. Let us squint at the example for understanding the concept in detail.

print("This is using locals() : ", locals())
print("n")
print("This is using globals() : ", globals())

Output:

locals() function for global environment

Explanation:

  • Firstly, we will print the locals() function.
  • Then, we will print a new line.
  • At last, we will print the globals() function.
  • Hence, we can see that the local symbol table is the same as the global symbol table in the specimen of the global environment.

5. Using locals() function inside a class

In this example, we will be using the locals() function inside the class. We will declare the matriculation name with python and inside the class, we will take a variable num which will be having the value 100. Then, we will undeniability the locals() function and see the output. Let us squint at the example for understanding the concept in detail.

class python:
    num = 100
    print('nlocals() value inside classn', locals())

Output:

inside a class

Explanation:

  • Firstly, we will declare a matriculation with name python.
  • Inside the class, we will declare a variable num which is equal to 100.
  • Then, we will undeniability the locals() function inside the matriculation only.
  • At last, we will be seeing the output.

6. Using locals() with list comprehension

In this example, we will be using the function in a list comprehension. But, the function has its own set of local variables as it is in a separate telescopic – thus yielding this unexpected behaviour. Let us squint at the example for understanding the concept in detail.

lang = ["python", "java", "c  ", "ruby", "go"]

newlist = [locals().get(var) for var in lang]

print(newlist)

Output:

locals() with list comprehension

Explanation:

  • Firstly, we will declare the list as lang with some languages in computer science.
  • We will then be applying the locals() function in the list comprehension and storing the output in the newlist.
  • At last, we are trying to print the new list.
  • Hence, we can see that the output shows unexpected policies as the list comprehension has its own set of local variables.

Difference between locals(), globals() and vars() function

locals() function

Python locals() function is an in-built function used to update and return a current local symbol table dictionary.

globals() function

Python globals() function is an in-built function used to update and return a wordlist of the current global symbol table.

To get the in-depth knowledge well-nigh the python globals() function click here.

vars() function

Python vars() function is an in-built function used to return a wordlist of the current namespace or the wordlist of argument. The main difference between vars() and locals() is that vars() can take an treatise and return a wordlist for the requested object.

To get the in-depth knowledge well-nigh the python vars() function click here.

If we write the locals() function and globals() function in the global environment, they will result in the same output. So, we will be taking an example with the help of function.

def func():
    num = 31
    print ("Locals : ", locals())
    print ("Vars : ", vars())
    print ("Globals : ", globals())
func()

Output:

Calling locals() in a function not intuitive?

In this example, we will see that calling a function is not intuitive. I thought the output would be like locals_1 would contain var; locals_2 would contain var and locals_1; and locals_3 would contain var, locals_1, and locals_2. But, the output is something else when I run the code. Let us squint at the example for understanding the concept in detail.

def func():
  var = 'var!'
  locals_1 = locals()
  locals_2 = locals()
  locals_3 = locals()
  return locals_1, locals_2, locals_3

# func is tabbed ...
locals_1, locals_2, locals_3 = func()

# exhibit results ...
print ('locals_1:', locals_1)
print ('locals_2:', locals_2)
print ('locals_3:', locals_3)

Output:

How to find keys in locals() python?

We can find keys in locals() python with the given code. As locals() returns a dictionary, you can use keys() to get all keys.

print(locals().keys())

Output:

Conclusion

In this tutorial, we have discussed the concept of the seated locals() function in python. We have seen what the locals() function, symbol table, and local symbol table is. Then, we have explained to you the syntax, parameter, and return value of the function. At last, we have explained the concept in detail with the help of variegated examples. All the examples are explained in detail with the help of examples. You can use any of the functions equal to your nomination and your requirement in the program.

However, if you have any doubts or questions, do let me know in the scuttlebutt section below. I will try to help you as soon as possible.

The post 6 Examples to Demystify Python locals() Function appeared first on Python Pool.

April 24, 2021 09:33 AM UTC


Nicola Iarocci

New Eve-Swagger and Flask-Sentinel releases

It’s maintenance day in my little Python world. I just released new versions of two small but theoretically quite popular packages:
eve-swagger, the OpenAPI/Swager extensions for Eve-powered APIs, hits v0.1.4. It’s just a each fix for API breakage introduced with the previous release; details misogynist here. Thanks to Asger Gitz-Johansen for the help with this release.
Flask-Sentinel, an Oauth2 Provider for Flask, hits v0.0.8. This moreover is a small release that fixes 500 errors if you were using unpinned versions of redis.

April 24, 2021 06:05 AM UTC

April 23, 2021


PyCharm

Slack is a popular tool for the workplace, unshut source projects, and plane personal messaging. With the onset of the pandemic and increasingly people working from home, Slack has wilt a increasingly vital piece of technology than overly before. Slack’s worthiness to create your own custom bots is a powerful full-length that allows you to customize your conversations and increase your productivity. This will be a live coding session where the finished product will be a deployed Slackbot that functions in your workspace.

webinar-Slackbot

Date: Thursday, April 29
Time: 17:00 UTC

The webinar will be held on the PyCharm YouTube channel. For Q&A we will be using YouTube yack during the whole webinar. Your questions, comments, and reactions are very welcome! We would like to make this online event as interactive as possible 🙂

REGISTER NOW!

About the presenter

Mason EggerMason Egger https://twitter.com/masonegger

Mason is a Developer Advocate at DigitalOcean who specializes in deject infrastructure, distributed systems, and Python. Prior to his work at DigitalOcean he was an SRE helping build and maintain a highly misogynist hybrid multicloud PaaS. He is an voracious programmer, speaker, educator, and writer/blogger. He contributes to random unshut source projects here and there and in his spare time he enjoys reading, camping, kayaking, and exploring new places.

 

April 23, 2021 04:43 PM UTC

Webinar “Building Your First Python Slackbot”

April 23, 2021 02:46 PM UTC


Python Software Foundation

Python Software Foundation Fellow Members for Q1 2021

The PSF is pleased to spoken its first batch of PSF Fellows in 2021! Let us welcome the new PSF Fellows for Q1! The pursuit people protract to do wondrous things for the Python community:

Briana Augenreich 

Georgi Ker 

Twitter, GitHub

Joe Banks

Twitter, GitHub

Leah Silen

Leon Sandøy

Twitter, Website, LinkedIn, GitHub, YouTube 

Sebastiaan Zeeff

Website, Twitter, LinkedIn

Zac Hatfield-Dodds

Website, GitHub

Thank you for your unfurled contributions. We have widow you to our Fellow roster online.

The whilom members help support the Python ecosystem by stuff phenomenal leaders, sustaining the growth of the Python scientific community, contributing to diversity efforts through PyLadies and other communities, maintaining virtual Python communities, maintaining Python libraries, creating educational material, organizing Python events and conferences, starting Python communities in local regions, and overall stuff unconfined mentors in our community. Each of them continues to help make Python increasingly wieldy virtually the world. To learn increasingly well-nigh the new Fellow members, trammels out their links above.

Let’s protract to recognize Pythonistas all over the world for their impact on our community. The criteria for Fellow members is misogynist online: https://www.python.org/psf/fellows/. If you would like to nominate someone to be a PSF Fellow, please send a unravelment of their Python upbringing and their email write to psf-fellow at python.org. We are unsuspicious nominations for quarter 2 through May 20, 2021.

April 23, 2021 02:23 PM UTC


Python for Beginners

Get key from value in dictionary

In python, we can get the values present in a wordlist using the keys by simply using the syntax dict_name[key_name]. But there isn’t any method to pericope a key associated with the value when we have values. In this article, we will see the ways with help of which we can get the key from a given value in a dictionary.

Get key from a value by searching the items in a dictionary

This is the simplest way to get a key for a value. In this method we will trammels each key-value pair to find the key associated with the present value.For this task, we will use the items() method for a python dictionary. The items() method returns a list of tuples containing key value pairs. We will search each tuple to find the key associated with our value as follows.

myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_items=myDict.items()
print("Given value is:")
myValue="PFB"
print(myValue)
print("Associated Key is:")
for key,value in dict_items:
    if value==myValue:
        print(key)

Output:

Dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
Given value is:
PFB
Associated Key is:
acronym

In the whilom program, we have  created a list of items in myDict using myDict.items() and then we trammels for each item in the list to find the key for our value. 

Get key from a value by using python lists

We can create a separate list of keys and values and then we can retrieve the keys from the given value using index() method. For this task, we will first create a list of keys present in the wordlist using keys() method and then we will create the list of values present in the wordlist using values() method. Now we will get the alphabetize of the given value from the list of values using index() method. As we know that the list of keys has the same order of keys as values in the list of values, the alphabetize of the values in the list of values will be the same as the alphabetize of the associated key in the list of keys. So, without finding the alphabetize of the value in the list of values, we can find the key in the list of keys at the same index. This can be washed-up as follows.

myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_keys=list(myDict.keys())
dict_values=list(myDict.values())
print("Given value is:")
myValue="PFB"
print(myValue)
val_index=dict_values.index(myValue)
print("Associated key is:")
myKey=dict_keys[val_index]
print(myKey)

Output:

Dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
Given value is:
PFB
Associated key is:
acronym

Get key from a value by using list comprehension

Instead of using index() method, we can use list comprehension to get the keys associated with the given value. To find the key, we will create a list of keys which have associated values equal to the given value using list comprehension as follows.


myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Dictionary is:")
print(myDict)
dict_items=myDict.items()
print("Given value is:")
myValue="PFB"
print(myValue)
print("Associated key is:")
myKey=[key for key,value in dict_items if value==myValue]
print(myKey)

Output:

Dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
Given value is:
PFB
Associated key is:
['acronym']

Conclusion

In this article, we have seen three ways to obtain a key from a python wordlist using list comprehension, items() method and list index() method. Stay tuned for increasingly informative articles.

The post Get key from value in wordlist appeared first on PythonForBeginners.com.

April 23, 2021 02:18 PM UTC


PyCharm

The first update of PyCharm 2021.1 brings some important bug fixes, including one that addresses an inability to find occurrences in files and in paths. It moreover provides improvements to the wits of working with Jupyter Notebooks, withal with updates to a variety of other features.

pc-2021-1

DOWNLOAD PYCHARM 2021.1.1

Here are the major improvements:

  • Find in Files: search is working well again. [IDEA-266391]
  • Python Console: we’ve disabled the auto-import full-length for the Python Console, so lawmaking completion should once then work smoothly there. [PY-47905]
  • Jupyter Notebooks: autoscroll from and to Source now works in a synchronized manner for the preview and editor panes. [PY-47976]
  • Jupyter Notebooks: the preview pane no longer freezes when the computer wakes up from a period of inactivity. [PY-45112]
  • Code insight: lawmaking completion for NumPy no longer suggests inappropriate options due to the updated NumPy stubs. [PY-48166]
  • Code insight: for the import plume action, only firsthand nature of the respective module or package are now suggested without a dot. [PY-47253]
  • PyCharm no longer scans the home directory for virtual environments if a custom (preferred) virtualenv directory is deleted. PyCharm will instead switch when to keeping virtual environments inside projects. [PY-47913]

The well-constructed list of improvements is misogynist in the release notes.

Download this version from our website. Alternatively, you can use the JetBrains Toolbox App to stay up to date.

Don’t forget to submit your bug reports and full-length requests to our tracker.

April 23, 2021 01:44 PM UTC


Stack Abuse

Guide to Using The Django MongoDB Engine with Python

Introduction

In this article, we will see how to use MongoDB, a non-relational database, with Django, a Python Web Framework.

Django is wontedly used with PostgreSQL, MariaDB or MySQL, all relational databases, due to it’s ORM under the hood. MongoDB, stuff quite flexible, is wontedly paired with lightweight frameworks such as Flask for the ease of prototyping. However, is moreover increasingly stuff used in larger projects due to scalability, dynamic structures and query support.

The Django MongoDB Engine is used to declaratively pinpoint schemas.

Note: At the time of writing, this engine doesn’t have the support for Python 3.x. The latest supported version is Python 2.7.

Non-relational vs Relational Databases

The key difference of this engine compared to other popular engines is that it works with a non-relational database, whereas Django applications are increasingly wontedly ripened with relational databases.

Choosing between these two approaches boils lanugo to the project you’re working on, as each type has unrepealable pros and cons depending on the situation. Non-relational databases are usually increasingly flexible (both a pro and con), while relational databases are increasingly conformed (also, both a pro and con).

Non-relational databases are also, usually, largest for scalable systems that hold a lot of data. However, for small-to-mid systems, the ease of maintaining relational databases oftentimes prevails.

Relational Database

A relational database stores data in tables, which consist of columns and rows.

  • A row represents an entity (e.g. a Movie)
  • A column represents an attribute of the entity (e.g. name of the movie, its length, year of release, etc.)
  • A row represents one entry in a database (e.g. {"The Matrix", 2h 16min, 1999.}).

Every table row should have a unique key (an ID), which represents solely that one row.

Some of the most famous relational databases are: Oracle, PostgreSQL, MySQL and MariaDB.

Non-relational Database

A non-relational database does not store data in tables, rather it depends on the type of data. There are four variegated types of non-relational databases:

  • Document-oriented Database (or Document Store)
    • Manages a set of named string fields usually in a form of JSON, XML or YAML documents. These formats can moreover have derivatives.
  • Wide-Column Store
    • Organizes data in columns, in a similar structure to relational databases
  • Graph Store
    • Stores relations between entities (most ramified type of non-relational database)
    • Used when data is widely interconnected
  • Key-Value Store
    • Simple key-value pair collection

Some of the most famous non-relational databases are: MongoDB, Cassandra, Redis.

relational vs non-relational databases

MongoDB is a document-based non-relational database, that saves documents in BSON (Binary JSON) format – a derivative of JSON.

Installation and Setup

To implement the Django MongoDB Engine in a project, we’ll want to install three things:

  1. Django-nonrel – Support for non-relational databases (This will moreover install Django 1.5 for you and uninstall any previously installed version).
  2. djangotoolbox – Tools for non-relational Django applications.
  3. Django MongoDB Engine – The engine itself.

Let’s install them via pip, slantingly Django itself:

$ pip install django
$ pip install git https://github.com/django-nonrel/django@nonrel-1.5
$ pip install git https://github.com/django-nonrel/djangotoolbox
$ pip install git https://github.com/django-nonrel/mongodb-engine

Let’s initialize a Django project via the command-line to get a starting point:

$ django-admin.py startproject djangomongodbengine

Now, with a skeleton project that contains some vital files, we’ll want to let Django know which engine we’d like to use. To do that, we’ll update our settings.py file, and increasingly specifically, the DATABASES property:

DATABASES = {
   'default' : {
      'ENGINE' : 'django_mongodb_engine',
      'NAME' : 'example_database'
   }
}

With the installation and setup done, let’s take a squint at some of the things we can do with the Django MongoDB Engine.

Models and Fields

When it comes to working with Models, in a standard MVC (Model-View-Controller) architecture, the archetype tideway is to use the django.db.models module. The Model matriculation has CharFields, TextFields, etc. that indulge you to substantially pinpoint the schema of your models and how they’ll be mapped to the database by Django’s ORM.

Let’s add a Movie model to our models.py:

from django.db import models

class Movie(models.Model)
    name = models.CharField()
    length = models.IntegerField()

Here, we have a Movie model that has two fields – name and length. Each of these are a Field implementation, which represents a database column, with the given data type.

While there are a pearly bit of field types, the models module doesn’t have unconfined support for fields that have multiple values.

This is mainly considering the models module is meant to mainly be used with relational databases. When an object has a field with multiple values, such as a Movie having many Actors, you’d have a One-to-Many relationship with flipside table.

With MongoDB, you can save them as a list within that document, without having to make a database reference to flipside table or document. This is where we finger the lack of fields such as ListField and DictField.

ListField

ListField is a list-type attribute, an symbol which can hold multiple values. It belongs to the djangotoolbox.fields module, and can be used to specify fields that contain list-like values, which are then saved into the BSON document.

Let’s tweak our Movie model from before:

from django.db import models
from djangotoolbox.fields import ListField

class Movie(models.Model):
    name = models.CharField()
    length = models.IntegerField()
    year = models.IntegerField()
    actors = ListField()

Note that we didn’t specify the id field. There is no need for it, since MongoDB will implicitly assign it to the instance of the Model. Additionally, we widow the actors field, which is a ListField.

Now, when creating a Movie instance, we can assign a list to the actors field, and save it to our MongoDB database as is, without creating a separate table to contain Actor instances and referencing them in our Movie documents:

movie = Movie.objects.create(
	name = "The Matrix",
	length = 136,
	year = 1999,
	actors = ["Keanu Reeves", "Laurence Fishburne"]
)

Running this piece of lawmaking results in a MongoDB document:

{
  "_id" : ObjectId("..."),
  "name" : "The Matrix",
  "length" : 136,
  "year" : 1999,
  "actors" : [
  	"Keanu Reeves", 
  	"Laurence Fishburne"
  ]
}

We can moreover extend() the ListField, and add increasingly values to it:

movie.actors.extend(['Carrie-Ann Moss'])

This results in an updated BSON document:

{
  "_id" : ObjectId("..."),
  "name" : "The Matrix",
  "length" : 136,
  "year" : 1999,
  "actors" : [
  	"Keanu Reeves", 
  	"Laurence Fishburne",
  	"Carrie-Ann Moss"
  ]
}

SetField

SetField is the same as ListField except that it’s interpreted as a Python set, which ways no duplicates are allowed.

If we add the same two-face twice:

movie.actors.extend(['Carrie-Ann Moss'])

We quickly realize that the output is a bit weird:

{
  "_id" : ObjectId("..."),
  "name" : "The Matrix",
  "length" : 136,
  "year" : 1999,
  "actors" : [
  	"Keanu Reeves", 
  	"Laurence Fishburne",
  	"Carrie-Ann Moss"
  ]
}

Since we’d like to stave indistinguishable entries, having each individual staying an very individual, it makes increasingly sense to make the actors a SetField instead of a ListField:

from django.db import models
from djangotoolbox.fields import ListField

class Movie(models.Model):
    name = models.CharField()
    length = models.IntegerField()
    year = models.IntegerField()
    actors = SetField()

Now, we can add multiple actors, some of which are duplicates, and we’ll only have unique additions:

movie = Movie.objects.create(
	name = "John Wick",
	length = 102,
	year = 2014,
	actors = ["Keanu Reeves", "Keanu Reeves", "Bridget Moynahan"]
)

However, the resulting document will only have one entry for "Keanu Reeves", the one and only:

{
  "_id" : ObjectId("..."),
  "name" : "John Wick",
  "length" : 102,
  "year" : 2014,
  "actors" : [
  	"Keanu Reeves", 
  	"Bridget Moynahan"
  ]
}

DictField

DictField stores Python dictionaries, as yet flipside BSON document, within your own document. These are preferable when you’re not sure what the wordlist might squint like – and you don’t have a pre-defined structure for it.

On the other hand if the structure is familiar, it is recommended to use Embedded Models, as models within models. For example, an Actor could be a model of its own, and we could let the Movie model have multiple embedded Actor models. On the other hand, if a variable set of values are to be added, they can be mapped as key-value elements and saved through a DictField.

For example, let’s add a reviews field, that can have 0..n reviews. While reviews do have a predictable structure (name, grade, comment), we’ll implement them as a DictField, surpassing making a separate Model for actors and reviews:

from django.db import models
from djangotoolbox.fields import SetField
from djangotoolbox.fields import DictField

class Movie(models.Model):
    name = models.CharField()
    length = models.IntegerField()
    year = models.IntegerField()
    actors = SetField()
    reviews = DictField()

Now, when creating movies, we can add dictionaries of reviewers, and their reviews of the movies:

movie = Movie.objects.create(
	name = "Good Will Hunting",
	length = 126,
	year = 1997,
	actors = ["Matt Damon", "Stellan Skarsgard"],
    reviews = [
        {"Portland Oregonian" : "With its sweet soul and sharp mind..."},
    	{"Newsweek" : "Gus Van Sant, working from the tangy, well-written script..."}
    ]
)

Running this lawmaking results in:

{
  "_id" : ObjectId("..."),
  "name" : "Good Will Hunting",
  "length" : 126,
  "year" : 1997,
  "actors" : [
  	"Matt Damon", 
  	"Stellan Skarsgard"
  ],
  "reviews" : [
  	{"Portland Oregonian" : "With its sweet soul and sharp mind..."},
    {"Newsweek": "Gus Van Sant, working from the tangy, well-written script..."}
  ]
}

Embedded Models

Now, the reviews field will, arguably, follow the same kind of structure – name followed by comment. actors value to increasingly than just their names – they have a last_name, date_of_birth and other characteristics.

For both of these, we can make standalone models, much like we’d make with relational databases. With relational databases, though, we’d save them in their own tables and link to them from the Movie table.

With MongoDB, we can turn them into Embedded Models – unshortened documents, embedded into flipside document.

Let’s transpiration our Movie once again:

from django.db import models
from djangotoolbox.fields import ListField, EmbeddedModelField


class Movie(models.Model):
    name = models.CharField(max_length=100)
    length = models.IntegerField()
    year = models.IntegerField()
    actors = SetField(EmbeddedModelField("Actor"))
    reviews = SetField(EmbeddedModelField("Review"))

Here, we’ve made a SetField (which could’ve moreover been something like a ListField) for both actors and reviews. However, this time around, we’ve made them SetFields of other models, by passing EmbeddedModelField into the constructors of SetFields.

We’ve moreover specified which models in the constructor of the EmbeddedModelField class.

Now, let’s pinpoint those two as well, in the models.py file:

class Actor(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
	date_of_birth = models.CharField(max_length=11)
    
class Review(models.Model):
    name = models.CharField(max_length=30)
    scuttlebutt = models.CharField(max_length=300)

Now, when creating a Movie object, and saving it into the database, we can moreover add new Actor and Review instances to it:

movie = Movie.objects.create(
	name = "Focus",
    length = 105,
    year = 2015,
    actors = [
        Actor(
            first_name="Will",
            last_name="Smith", 
            date_of_birth="25.09.1968."
        )
    ],
    reviews = [
        Review(
            name = "Portland Oregonian",
            scuttlebutt = "With its sweet soul and sharp mind..."
        ),
        Review(
            name = "Newsweek",
            scuttlebutt = "Gus Van Sant, working from the tangy, well-written script..."
        )
    ]
)

This creates new BSON documents for each Actor and Review in the sets, and saves them as embedded objects into our movie document:

{
  "_id" : ObjectId("..."),
  "name" : "Focus",
  "length" : 105,
  "year" : 2015,
  "actors" : [
      {
          "name" : "Will",
          "last_name" : "Smith",
          "date_of_birth" : "25.09.1968"
        }   
    ],
    "reviews" : [
        {
          "name" : "Portland Oregonian",
          "comment" : "With its sweet soul and sharp mind..."
        },
        {
          "name" : "Newsweek",
          "comment" : "Gus Van Sant, working from the tangy, well-written script..."
        }
    ]
}

Each entry in the reviews BSON variety is an individual Review instance. Same goes for actors.

File Handling

MongoDB has a seated specification for storing/retrieving files in the filesystem tabbed GridFS, which is used in the Django MongoDB Engine too.

Note: MongoDB stores files by separating them in pieces sized 255 kB each. When the file is accessed, GridFS collects the pieces and merges them.

To import the GridFS system, we’ll wangle the django_mongodb_engine_storage module:

from django_mongodb_engine.storage import GridFSStorage

gridfs = GridFSStorage()
uploads_location = GridFSStorage(location = '/uploaded_files')

Another field we can use is the GridFSField(), which allows us to specify fields that utilize the GridFS system to store data:

class Movie(models.Model):
    name = models.CharField()
    length = models.IntegerField()
    year = models.IntegerField()
    actors = SetField(EmbeddedModelField("Actor"))
    reviews = SetField(EmbeddedModelField("Review"))
    poster = GridFSField()

Now this image will be saved in chunks and lazy-loaded only on demand.

Conclusion

To sum up, the Django MongoDB Engine is a fairly powerful engine and the main downside of using it is that it works with old versions of Django (1.5) and Python (2.7), whereas Django is now at 3.2 LTS and the support for 1.5 ended a long time ago. Python is at 3.9 and support for 2.7 ended last year. In wing to all of that, Django MongoDB Engine seems to has stopped remoter minutiae when in 2015.

April 23, 2021 12:30 PM UTC


Real Python

The Real Python Podcast – Episode #57: Taking the Next Step in Python Game Development

Are you interested in creating video games but finger limited in what you can succeed within Python? Is there a platform where you can take wholesomeness of your Python skills and provide the benefits of a defended game engine? This week on the show, we have Paweł Fertyk. Paweł is a Real Python tragedian and has been creating games as Miskatonic Studio for several years now.


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

April 23, 2021 12:00 PM UTC


PyCharm

PyCharm 2021.1.1: Improved Indexing and Jupyter Notebooks Experience

April 23, 2021 10:37 AM UTC


Python Pool

How to Save a Variable in a File in Python

In python, we have discussed many concepts and conversions. But sometimes, we come to a situation where we need to read a text from a file, write a text from a file, suspend a text in a file, and save a file in python. In this tutorial, we will be discussing how to save a variable in a file.

What are file wangle modes?

Access modes are used to govern the type of operations possible in the opened file. It tells us well-nigh how the file will be used once it’s opened. These modes pinpoint the location of the file handle in the file. The file handle is just like a cursor, which tells from where the data has to be read or written in the file. We have 6 modes in python:

  • Read-only (‘r’): It only opens text files for reading. If the file does not exist, it raises the IO error. This is the default mode in which the file is opened.
  • Write only (‘w’): It opens the file for writing. If the file exists previously, the data is truncated and over-write the data. it creates the file if the filename does not exist.
  • Read and Write (‘r ’): It opens the file for reading and writing. It raises an I/O error if the file does not exist.
  • Write and read (‘w ’): It opens the file for reading and writing. If the file exists, the data is over-written.
  • Append only (‘a’): It opens the file for writing. If the file does not exist, it gets created. The data which is written gets appended at the last of the data which is once written.
  • Append and read (‘a ’): It opend=s a file for reading and writing. The file gets created if does not exist. The data which is stuff written is inserted at the end of the data, without the existing data.

Many times a user or a python programmer needs to delete or rename a file. To know how to execute these tasks you can read our posts from here:

Ways to save a variable in a file in python

Here, we will be discussing all the variegated ways through which we can save a variable in a file in python:

1. Using string concatenation to save a variable in a file in Python

In this example, we will use open(file, mode) with the file’s pathname as files and mode as ‘w’ to unshut the file for writing. Then, we will use repr(object) with the object as the variable to convert a variable to a string. Without that, we will undeniability the file.write(data) with data as a string concatenation of three strings, a string containing the variable name and = the string version of the variable, and "n". At last, we will use a file.close() to tropical the file. Let us squint at the example for understanding the concept in detail.

#input text
dict = {"one" : 1, "two" : 2}

#open file
file = open("Python.txt", "w")

#convert variable to string
str = repr(dict)
file.write("dict = "   str   "n")

#close file
file.close()

f = open('Python.txt', 'r')
if f.mode=='r':
    contents= f.read()

Output:

Using string concatenation to save a variable in a file in Python

Explanation:

  • Firstly, Then, we will take an input wordlist with two values in it.
  • Then, we will unshut the file with file = open(). We have passed the file name and ‘w’ as the write mode as the parameter.
  • Then, we will convert the variable into the string with the repr() function.
  • Then, we will wield file.write() in which we have passed the input dictionary.
  • At last, we will be latter the file with file.close().
  • Hence, you can see the data gets saved in the particular file.

2. Using String formatting to save a variable in a file in Python

In this example, we will be using open(file, mode) with the file’s pathname as a file and modes as ‘w’ to unshut the file for writing. Then, we will undeniability the file.write(data) with data as the string formats “%s %d” followed by % and a tuple containing a string of the variable name and the variable. At last, we will tropical the file by using file.close(). Let us squint at the example for understanding the concept in detail.

#input variable
dict = {"one" : 1, "two" : 2}

file = open("Python.txt", "w")
file.write("%s = %sn" %("dict", dict))

file.close()

f = open('Python.txt', 'r')
if f.mode=='r':
    contents= f.read()

Output:

Using String formatting

Explanation:

  • Firstly, Then, we will be taking an input wordlist with two values in it.
  • Then, we will unshut the file with file = open(). Inside which we have passed the file name and ‘w’ as the write mode as the parameter.
  • Then, we will wield file.write() in which we have passed the input dictionary.
  • At last, we will be latter the file with file.close().
  • Hence, you can see the data gets saved in the particular file.

3. By importing pickle library to save a variable in a file

In this example, we will be importing the pickle library. Then, we will be using open(file, mode) with the pathname of a file as a file and modes as ‘w’ to unshut the file for writing. Without that, we will wield the pickle library with the parameters as dict and file as a variable. At last, we will tropical the file by using file.close(). Let us squint at the example for understanding the concept in detail.

import pickle
dict = {'one': 1, 'two': 2}
file = open('Python.txt', 'w')
pickle.dump(dict, file)
file.close()

with open('Python.txt', 'rb') as f:
    dict = pickle.load(f)

Output:

By importing pickle library to save a variable in a file

Explanation:

  • Firstly, we will be importing the pickle module.
  • Then, we will be taking an input wordlist with two values in it.
  • Then, we will unshut the file with file = open(). We have passed the file name and ‘w’ as the write mode as the parameter.
  • After that, we will wield the dump() function from the pickle module, which will dump all the data into the particular file.
  • At last, we will tropical the file with file.close().
  • Hence, you can see the output.

4. Using numpy library to save a variable in a file

In this example, we will be importing a numpy library with an plume name as np. Then we will be taking two lists: a and b. Then, we will wield the savetxt() function from the numpy library. Let us squint at the example for understanding the concept in detail.

import numpy as np
a = [1,2,3,4,5]

np.savetxt('Python.txt',a)

print(open("E:python.txt").read())

Output:

Explanation:

  • Firstly, we will be importing the numpy module with an plume name as np.
  • Then, we will be taking input as a list in the variable a.
  • Then, we will wield the savetxt() function from the numpy library.
  • Inside which we have passed the file name and the list as the parameter.
  • At last, if we unshut the same file, we will see the output as shown.
  • Hence, you can see the output is saved in the given file.

Conclusion

In this tutorial, we have learned well-nigh the concept of saving a variable in a file in python. We have seen all the wangle modes in the file. Without that, we have discussed all the ways through which we can save a variable in a file in python. All the ways are explained in detail with the help of examples. You can use any of the functions equal to your nomination and your requirement in the program.

However, if you have any doubts or questions, do let me know in the scuttlebutt section below. I will try to help you as soon as possible.

The post How to Save a Variable in a File in Python appeared first on Python Pool.

April 23, 2021 09:32 AM UTC


Full Stack Python

How to Monitor Python Functions on AWS Lambda with Sentry

Amazon Web Services (AWS) Lambda is a usage-based
compute service that can run Python 3 code. Errors
can happen in any environment you are running your using in, so
it is necessary to have reliable monitoring in place
to have visibility when a problem occurs.

In this post we will install and configure
Sentry’s using monitoring
service that works specifically for lawmaking running on AWS Lambda.

Application Dependencies

A local minutiae environment is not
required to follow this tutorial considering all of the coding and configuration
can happen in a web browser through the
AWS Console.

The example lawmaking can be reprinting and pasted from this blog post or you
can wangle it on GitHub under the
Full Stack Python blog-post-examples
repository within the
monitor-python-aws-lambda-sentry directory.

Accessing the AWS Lambda Service

Sign into your existing AWS account
or sign up for a new account. Lambda
gives you the first 1 million requests for self-ruling so that you can execute
basic applications without no or low cost.

The AWS Lambda landing page.

When you log into your account, use the search box to enter
“lambda” and select “Lambda” when it appears to get to the right
page.

Use the search bar to find AWS Lambda.

If you have once used Lambda before, you will see your existing Lambda
functions in a searchable table. We’re going to create a new function so
click the “Create function” button.

Click the create function button.

The create function page will requite you several options for starting a new
Lambda function.

The create function details page.

Click the “Browse Serverless App Repository” selection box, then choose
the “hello-world-python3” starter app from within the
“Public applications” section.

The create function details page.

The hello-world-python3 starter app details page should squint something
like the pursuit screen:

Hello world Python3 example app and Lambda function.

Fill in some example text such as “test” under IdentityNameParameter
and click the “Deploy” button:

Click the deploy sawed-off to use the starter app.

The function will now be deployed. As soon as it is ready we can
customize it and test it out surpassing subtracting Sentry to capture any errors
that occur during execution.

Testing the starter Python app

Go when to the Lambda functions main page and select your new deployed
starter app from the list.

List of AWS Lambda functions you have created.

Find the orange “Test” sawed-off with a lanugo thunderstroke next to it like you
see in the image below, and then click the lanugo arrow. Select
“Configure Test Event”.

Configure the test event.

Fill in the Event name as “FirstTest” or something similar, then
press the “Create” sawed-off at the marrow of the modal window.

Click the “Test” sawed-off and it will run the Lambda function with
the parameters from that new test event. You should see something
like the pursuit output:

Response
"value1"

Function Logs
START RequestId: 62fa2f25-669c-47b7-b4e7-47353b0bd914 Version: $LATEST
value1 = value1
value2 = value2
value3 = value3
END RequestId: 62fa2f25-669c-47b7-b4e7-47353b0bd914
REPORT RequestId: 62fa2f25-669c-47b7-b4e7-47353b0bd914  Duration: 0.30 ms   Billed Duration: 1 ms   Memory Size: 128 MB Max Memory Used: 43 MB  Init Duration: 1.34 ms

Request ID
62fa2f25-669c-47b7-b4e7-47353b0bd914

That ways the test specimen was successful, but what happens plane if there
is a straightforward mistake in the code, such as trying to wangle an
undeclared variable?

Go into the lawmaking editor and you should see the starter lawmaking like this:

Code editor within AWS Lambda.

Update the lawmaking with the new highlighted line, which tries to access
a fourth variable, which does not exist in the test configuration
we try to run it with.

import json

print('Loading function')


def lambda_handler(event, context):
    #print("Received event: "   json.dumps(event, indent=2))
    print("value1 = "   event['key1'])
    print("value2 = "   event['key2'])
    print("value3 = "   event['key3'])
~~    print("value4 = "   event['key4'])
    return event['key1']  # Echo when the first key value
    #raise Exception('Something went wrong')

After subtracting that one new line of code, hit the “Deploy” button,
then the “Test” button. You should see some error output:

Response
{
  "errorMessage": "'key4'",
  "errorType": "KeyError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      11,
      "lambda_handler",
      "print("value4 = "   event['key4'])"
    ]
  ]
}

Function Logs
START RequestId: a4e956bd-cce4-403e-b5e7-e95bc3ffa2cb Version: $LATEST
value1 = value1
value2 = value2
value3 = value3
'key4': KeyError
Traceback (most recent undeniability last):
  File "/var/task/lambda_function.py", line 11, in lambda_handler
    print("value4 = "   event['key4'])
KeyError: 'key4'

END RequestId: a4e956bd-cce4-403e-b5e7-e95bc3ffa2cb
REPORT RequestId: a4e956bd-cce4-403e-b5e7-e95bc3ffa2cb  Duration: 0.81 ms   Billed Duration: 1 ms   Memory Size: 128 MB Max Memory Used: 43 MB  Init Duration: 1.61 ms

Request ID
a4e956bd-cce4-403e-b5e7-e95bc3ffa2cb

It is obvious when we are working in the Panel that an error just
occurred. However, in most cases an error will happen sporadically
which is why we need a monitoring system in place to reservation and report
on those exceptions.

AWS Lambda function monitoring with Sentry

The easiest way to add Sentry to Lambda for this application
is to configure an
AWS Lambda Layer
with the necessary dependency for Sentry. Sentry has concise
documentation on addin gvia Lambda Layers
so we will walk through that way to configure it and test it
out.

First, scroll lanugo to the “Layers” section while in your Lambda
function configuration. Click the “Add a layer” button”:

Add Lambda layer.

In the “Add layer” screen, select the “Specify an ARN” option.

Select Specify ARN in the Add Layer screen.

Now to specify the Amazon Resource Name (ARN), we need to use
the Sentry documentation to get the right configuration string.

US-East-1 is the oldest and most commonly-used region so I’ll
use that here in this tutorial but you should trammels which one
you are in if you are not certain.

Select the AWS for the ARN string.

Copy that value into the Lambda Layer configuration, like this:

Select the AWS for the ARN string.

Then printing the “Add” button. Now you have the Sentry dependency
in your environment so lawmaking that relies upon that library can be
used in the Lambda function.

Next we need to go into the Sentry dashboard to create a project,
get our unique identifer, and connect it to our Lambda function.

Sentry can be self-hosted or
used as a deject service through Sentry.io. We will
use the deject hosted version considering it is quicker than
setting up your own server as well as self-ruling for smaller projects.

Go to Sentry.io’s homepage.

Sentry.io homepage where you can sign up for a self-ruling account.

Sign into your worth or sign up for a new self-ruling account. You will be at
the main worth dashboard without logging in or completing the Sentry sign
up process.

There are no errors logged on our worth dashboard yet, which is as
expected considering we have not yet unfluctuating our worth to our Lambda
function.

Click “Projects” on the left navigation bar, then “Create Project”
in the top right corner.

Under “Choose a Platform”, select “Serverless” and then “AWS Lambda (Python)”
as shown below:

Choose AWS Lambda (Python) under the platform options.

Decide under what criteria it should send error information out of
Lambda. For this tutorial, we will have it send every exception.
Then click the “Create Project.” button.

You can have Sentry handle the instrumentation automatically but
we will handle it manually for our function. On the next screen, Sentry
will provide you with your unique DSN string, which we will need for
our function.

Copy the Sentry DSN string so we can export it as an environment variable.

Typically you will want to
use environment variables on AWS Lambda
to store and wangle values like your Sentry key.

Copy the contents of the Sentry DSN string, and go into the Lambda console
to create a new environment variable. To do that, click the “Configuration”
tab within Lambda like you see here:

Click the Lambda Configuration tab.

Then click “Edit” and add a new environment variable with the key of SENTRY_DSN
and the value of the DSN string that you copied from the Sentry screen.

Add the environment variable in AWS Lambda.

Click the “Save” sawed-off and go when to your Lambda function code.

Update your Lambda function with the pursuit highlighted new lines of code
to send errors to Sentry.

import json
~~import os
~~import sentry_sdk
~~from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration

~~SENTRY_DSN = os.environ.get('SENTRY_DSN')
~~sentry_sdk.init(
~~    dsn=SENTRY_DSN,
~~    integrations=[AwsLambdaIntegration()]
~~)

print('Loading function')


def lambda_handler(event, context):
    #print("Received event: "   json.dumps(event, indent=2))
    print("value1 = "   event['key1'])
    print("value2 = "   event['key2'])
    print("value3 = "   event['key3'])
    print("value4 = "   event['key4'])
    return event['key1']  # Echo when the first key value
    #raise Exception('Something went wrong')

Click the “Deploy” sawed-off and then “Test”. The lawmaking will throw
an error and when we go when to our Sentry dashboard we will
see it captured and viewable for remoter inspection.

AWS Lambda exception in the Sentry dashboard.

It works! Next you will likely want to tune your exception reporting
criteria to make sure you get alerted to the right number of exceptions
if you do not want to see all of them.

What’s Next?

We just wrote and executed a Python 3 function on AWS Lambda then
captured the exception message into the Sentry logs. You can
now protract towers out your Python lawmaking knowing that when something
goes wrong you will have full visibility on what happened.

Check out the AWS Lambda section for
more tutorials by other developers.

Further questions? Contact me on Twitter
@fullstackpython
or @mattmakai. I am moreover on GitHub with
the username mattmakai.

Something wrong with this post? Fork
this page’s source on GitHub
and submit a pull request.

April 23, 2021 04:00 AM UTC

April 22, 2021


Paolo Melchiorre

GeoPython 2021

The Python online event for Python, Geo- and Machine Learning-Enthusiasts.

April 22, 2021 10:00 PM UTC


The No Title® Tech Blog

New project: Optimize Images X

Just for fun, this month I set myself to start a new Python project. It’s the same as Optimize Images, but with a big X and a nice graphical user interface. It wants to help you reduce the file size of images, and hopefully make your websites load faster.

April 22, 2021 09:00 PM UTC


Reuven Lerner

It’s time to learn Python

I’m on a mission: I want to help people to do increasingly in less time, and to have largest careers. How? Using Python.

If you’re reading this, then you might once be convinced that Python is both easy to learn and impressively powerful. And you hopefully goody from this power, either in your day-to-day work or as you tinker on personal projects.

But a lot of people aren’t quite convinced, or don’t yet know:

  • Non-programmers think that programming is arcane, difficult to learn, or just irrelevant to their work. And besides, the way they currently do things is good enough, right?
  • Experienced developers, meanwhile, wonder why they should learn Python, when they can do just fine with other languages. I often hear this in my corporate training classes — until those hard-core developers see how much can be washed-up with a handful of lines of Python.

I know, from experience, that no matter what your background, Python can help you to wilt increasingly productive. And the number of companies looking for people with Python experienced continues to grow quickly, which ways that having it on your resume gives you a leg up on other candidates.

On Wednesday, I’m holding a free, hour-long Webinar aimed at people who haven’t yet discovered the power and magic of Python. I’ll talk well-nigh why it’s a unconfined language, and what people are doing with it. There will moreover be plenty of time for Q&A.

I hope to inspire people to start learning Python. And yes, I’ll moreover be pitching my courses as one way to make that move.

You can learn more, and register to join me, at https://FiveReasonsToLearnPython.com/.

Now, if you’re once an old hand at Python, then you probably don’t need convincing. But perhaps you have colleagues who aren’t sure if Python is a worthwhile investment of their time. Or maybe you have friends who have considered it, but aren’t completely sure.

And if you’re new to Python, like increasingly than half of the people getting my free, weekly “Better developers” newsletter? Then you’ll scrutinizingly certainly learn something new well-nigh the language, and ways to use it that you hadn’t considered before.

Questions? Contact me at reuven@lerner.co.il or as @reuvenmlerner on Twitter, and I’ll be happy to answer. But I moreover hope to see you on Wednesday!

Again, join me, for free, at https://FiveReasonsToLearnPython.com/.

The post It’s time to learn Python appeared first on Reuven Lerner.

April 22, 2021 02:54 PM UTC


Python for Beginners

Merge Dictionaries in Python

While programming, there may be situations where we need to merge two or increasingly dictionaries in python. In this article, we will study how we can merge two or increasingly dictionaries in python using variegated ways.

Merge dictionaries using items() method.

We can merge two dictionaries using items() method by subtracting items of a wordlist to flipside wordlist one by one. The items() method when invoked on a dictionary, returns a list of tuples containing the key value pair. If we have to merge two dictionaries, we will take items of a wordlist one by one and add it to flipside wordlist as follows. 

dict1={1:1,2:4,3:9}
print("First wordlist is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second wordlist is:")
print(dict2)
for key,value in dict2.items():
    dict1[key]=value
print("Merged wordlist is:")
print(dict1)

Output:

First wordlist is:
{1: 1, 2: 4, 3: 9}
Second wordlist is:
{4: 16, 5: 25, 6: 36}
Merged wordlist is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

While using the whilom method, we have to consider the point that if there are worldwide keys between the two dictionaries, the final wordlist will have worldwide keys with values from the second wordlist from which we have extracted the items. Moreover only the first dictionary, to which the items are stuff widow gets modified and nothing happens to the second dictionary.

Merge dictionaries using popitem() method.

The popitem() method is used to delete an item from a python dictionary. When invoked on a wordlist the popitem() method deletes the most recently widow item in the wordlist and returns the item in the form of a tuple as key value pair.

To merge the dictionaries, we will pop the items from a wordlist using the popitem() method and will alimony subtracting it to flipside dictionary.

dict1={1:1,2:4,3:9}
print("First wordlist is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second wordlist is:")
print(dict2)
while dict2:
    key,value=dict2.popitem()
    dict1[key]=value
print("Merged wordlist is:")
print(dict1)

Output:

First wordlist is:
{1: 1, 2: 4, 3: 9}
Second wordlist is:
{4: 16, 5: 25, 6: 36}
Merged wordlist is:
{1: 1, 2: 4, 3: 9, 6: 36, 5: 25, 4: 16}

While using the whilom method, we have to alimony in mind that both the dictionaries which are to be merged get modified. The second wordlist from which the items are stuff pooped out becomes empty while the first wordlist to which items are stuff widow moreover gets modified. Again, we will have to consider the point that if there are worldwide keys between the dictionaries which are stuff merged, the merged wordlist will contain values from the second wordlist from which the items were popped out for the worldwide keys.

Using keys() method.

We can moreover use keys() method to merge two dictionaries in python. The keys() method when invoked on a dictionary, returns the list of keys in the dictionary. We will use the keys() method to take all the keys from a wordlist and without that we can wangle the associated values of the keys. Without that we can add the key value pair into flipside wordlist as follows.  

dict1={1:1,2:4,3:9}
print("First wordlist is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second wordlist is:")
print(dict2)
keylist=dict2.keys()
for key in keylist:
    dict1[key]=dict2[key]
print("Merged wordlist is:")
print(dict1)

Output:

First wordlist is:
{1: 1, 2: 4, 3: 9}
Second wordlist is:
{4: 16, 5: 25, 6: 36}
Merged wordlist is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

When we merge two dictionaries using whilom method in python , we have to alimony in mind that second wordlist from which we are getting the keys doesn’t get modified. Only the wordlist to which keys and values are getting widow gets modified. Also, if the two dictionaries stuff merged have keys in worldwide then the merged wordlist will have the values for the worldwide keys from the wordlist from which the keys were obtained.

Merge dictionaries using update() method

We can directly merge a wordlist to flipside wordlist using update() method. The update() method is invoked on a wordlist and it takes flipside wordlist as input argument. We can merge the dictionaries using the update() method as follows.

dict1={1:1,2:4,3:9}
print("First wordlist is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second wordlist is:")
print(dict2)
dict1.update(dict2)
print("Merged wordlist is:")
print(dict1)

Output:

First wordlist is:
{1: 1, 2: 4, 3: 9}
Second wordlist is:
{4: 16, 5: 25, 6: 36}
Merged wordlist is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

In this case, when we merge two dictionaries using update() method in python, the worldwide keys are prescribed the values which are present in the wordlist which is passed as argument. Moreover the second wordlist which is passed as treatise doesn’t get modified while the first wordlist on which the update() method is invoked gets modified and is turned into final dictionary.

Merge dictionaries using ** operator

Double asterisk (**) operator is used to pass variable length keyword parameters to a function. We can moreover use ** operator to merge two dictionaries. When we wield ** operator to a dictionary, it deserializes the wordlist and converts it to a hodgepodge of key value pairs and then a new wordlist is worked using the key value pairs.

dict1={1:1,2:4,3:9}
print("First wordlist is:")
print(dict1)
dict2={4:16,5:25,6:36}
print("Second wordlist is:")
print(dict2)
mergedDict={**dict1,**dict2}
print("Merged wordlist is:")
print(mergedDict)

Output:

First wordlist is:
{1: 1, 2: 4, 3: 9}
Second wordlist is:
{4: 16, 5: 25, 6: 36}
Merged wordlist is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

We can merge any number of dictionaries at once using ** operator. Also, none of the original dictionaries which have to be merged are modified. They remain as it is. In this method too, when the dictionaries to be merged have worldwide keys, the values for the respective keys will be taken from the dictionaries which come last in the sequence while merging.

Conclusion

In this article, we have seen how to merge dictionaries in python using variegated methods. We can moreover write the programs used in this vendible with exception handling using python try except to make the programs increasingly robust and handle errors in a systematic way. Stay tuned for increasingly informative articles.

The post Merge Dictionaries in Python appeared first on PythonForBeginners.com.

April 22, 2021 12:44 PM UTC


Stack Abuse

Plotly Bar Plot – Tutorial and Examples

Introduction

Plotly is a JavaScript-based, Python data visualization library, focused on interactive and web-based visualizations. It has the simplicity of Seaborn, with a high-level API, but moreover the interactivity of Bokeh.

In wing to the cadre library’s functionality, using the seated Plotly Express with Dash, makes it an wondrous nomination for web-based applications and interactive, data-driven dashboards, usually written in Flask.

In this guide, we’ll take a squint at how to plot a Bar Plot with Plotly.

Bar charts are most wontedly used to visualize well-defined data, where the height of each bar represents the number of occurrences in that category.

Plot a Bar Plot with Plotly

To plot a Bar Plot in Plotly, you simply undeniability the bar() function of the Plotly Express (px) instance, providing the x and y arguments with valid data:

import plotly.express as px

x = ['Category 1', 'Category 2', 'Category 3']
y = [5, 3, 6]

fig = px.bar(x, y)
fig.show()

Here, we have three categories, as a list that we’ve provided to the x treatise and a few scalar values we’ve provided to the y argument. This results in a simple and intuitive Bar Plot:

alt

However, we rarely work with lists when doing Data Visualization. Let’s import the Telecom Users Dataset and visualize the InternetService and tenure features through a Bar Plot.

The InternetService full-length is a well-defined feature, that specifies which type of service the consumer is using, while the tenure is a numerical full-length that represents how long a consumer has been with the company, in months:

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')
print(df.head())

This results in:

   gender  SeniorCitizen  tenure InternetService ...
0    Male              0      72              No ...
1  Female              0      44     Fiber optic ...
2  Female              1      38     Fiber optic ...
3    Male              0       4             DSL ...
4    Male              0       2             DSL ...

Now, let’s go superiority and plot this data as a Bar Plot:

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')

fig = px.bar(df, x = 'InternetService', y = 'tenure')
fig.show()

To plot data from a dataset, we’ve provided the data source (df) as the first argument, and the post names we’d like to visualize to the x and y arguments. Plotly maps these, fetches the data and generates a plot:

alt

Now, the plot generated by Plotly unquestionably separates each instance into a small stacked bar of its own on this plot, since several rows share the same x value, unlike the simple 1-to-1 mapping like we had in the first example.

We can see the cumulative number of months they’ve served to their customers, in parallel. While ~90K months may seem like an insane number of months (7500 years), the median tenure is 29 months:

print(df['tenure'].median()) # 29.0

Change Bar Plot Colors with Plotly

It’s easy to transpiration the colors of each of the same instances, based on any other variable present in the dataset. These are most often other well-defined features, such as gender or SeniorCitizen.

Grouping instances by flipside full-length creates a Grouped Bar Plot, which are most wontedly plotted one next to the other. By simply coloring instances based on flipside feature, we’ll have a Stacked Grouped Bar Plot, since we’ll have two or increasingly groups of instances one on top of the other.

Let’s take a squint at the Bar Plot once again, once we verisimilitude each plot depending on the gender feature:

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')

fig = px.bar(df, x = 'InternetService', y = 'tenure', color='gender')
fig.show()

Now, the default Plotly color-scheme will apply, and the instances will be sorted by verisimilitude so they’re not mish-mashed throughout the plot:

alt

Since we’ve got multiple rows sharing the same x values – these are plotted, essentially, as stacked grouped bars.

If we were to plot a variegated feature, that doesn’t stack (isn’t a binary nomination of flipside feature), the plot would squint fairly differently:

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')

fig = px.bar(df, x='tenure', y='MonthlyCharges', color='tenure')

fig.show()

alt

When providing many verisimilitude values, such as 0..70 via the tenure full-length – you’ll see trappy gradients worked in your plots.

Plot Grouped Bar Plot with Plotly

Sometimes, it’s easier to differentiate if we plot the bars one next to the other, instead of stacking them on top of each other. This is particularly useful when we have binary features, such as SeniorCitizen that only has two values. You can really have n values in features you group by, though, most groups don’t really goody us much if they’re too large.

To do this, we can simply update the layout of the Figure, and set the barmode to 'group':

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')

fig = px.bar(df, x = 'InternetService', y = 'tenure', color='gender')
fig.update_layout(barmode='group')
fig.show()

Now, it’s much easier to compare the number of instances:

alt

Plot a Horizontal Bar Plot with Plotly

To plot a Bar Plot horizontally using Plotly, we can set the orientation treatise to h (as opposed to the default v) while plotting the Bar Plot:

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')

fig = px.bar(df, x='MonthlyCharges', y='tenure', color='tenure', orientation='h')

fig.show()

Keep in mind that if you’d like to alimony the X-Y relationship as it was before, you’ll switch the x and y arguments. Running this lawmaking results in:

alt

Ordering Bar Plots in Plotly

Plotly automatically orders the bars. You can directly modify this setting by updating the Figure parameters.

You can opt for transmission ordering, or will-less ordering. For transmission ordering, you can pass in a wordlist that contains the names of the features and their order, which will result in a stock-still order, to the category_orders argument:

import pandas as pd
import plotly.express as px

df = pd.read_csv('telecom_users.csv')

fig = px.bar(df, x='InternetService', y='tenure', color='gender',
             category_orders={"InternetService": ["DSL", "Fiber optic", "No"],
                              "gender": ["Female", "Male"]})
fig.show()

Here, we’ve ordered the InternetService full-length in a explicit order, that we’ve manually set, as well as the gender feature.

Plotting the Bar Plot now will result in:

alt

Alternatively, expressly if there’s a large number of possible values – we might want to let Plotly automatically sort and order values of features. We can either sort them categorically or numerically.

And both of these can remoter be ordered in ascending or descending order. To order numerically, we invoke the total keyword, while we invoke the category keyword for well-defined ordering.

By default, Plotly adjusts the ordering based on the provided data – in our case, it ordered it as total ascending. Let’s transpiration that virtually to total descending:

fig.update_layout(xaxis={'categoryorder':'total descending'})

This results in:

alt

When ordering categorically, it sorts lexicographically:

fig.update_layout(xaxis={'categoryorder':'category ascending'})

This results in:

alt

Conclusion

In this tutorial, we’ve taken a quick squint at how to plot and customize Bar Plots with Plotly.

If you’re interested in Data Visualization and don’t know where to start, make sure to trammels out our bundle of books on Data Visualization in Python:

Data Visualization in Python with Matplotlib and Pandas is a typesetting planned to take wool beginners to Pandas and Matplotlib, with vital Python knowledge, and indulge them to build a strong foundation for wide work with theses libraries – from simple plots to turned-on 3D plots with interactive buttons.

It serves as an in-depth, guide that’ll teach you everything you need to know well-nigh Pandas and Matplotlib, including how to construct plot types that aren’t built into the library itself.

Data Visualization in Python, a typesetting for beginner to intermediate Python developers, guides you through simple data manipulation with Pandas, imbricate cadre plotting libraries like Matplotlib and Seaborn, and show you how to take wholesomeness of declarative and experimental libraries like Altair. Increasingly specifically, over the span of 11 chapters this typesetting covers 9 Python libraries: Pandas, Matplotlib, Seaborn, Bokeh, Altair, Plotly, GGPlot, GeoPandas, and VisPy.

It serves as a unique, practical guide to Data Visualization, in a plethora of tools you might use in your career.

April 22, 2021 12:30 PM UTC


Talk Python to Me

#313 Automate your data mart with PyDantic

Data validation and conversion is one of the truly tricky part of getting external data into your app. This might come from a REST API, a file on disk, or somewhere else. This includes checking for required fields, correct data types, converting from uniform types (for example, strings to numbers), and much more. Pydantic is one of the weightier ways to do this in modern Python using dataclass-like constructs and type annotations to make it all seamless and automatic.
<br/>

<br/>
We welcome Samuel Colvin, creator of Pydantic, to the show. We’ll swoop into the history of Pydantic and it’s many uses and benefits.<br/>
<br/>
<strong>Links from the show</strong><br/>
<br/>
<div><b>Samuel on Twitter</b>: <a href=”https://twitter.com/samuel_colvin” target=”_blank” rel=”noopener”>@samuel_colvin</a><br/>
<b>pydantic</b>: <a href=”https://pydantic-docs.helpmanual.io/” target=”_blank” rel=”noopener”>pydantic-docs.helpmanual.io</a><br/>
<b>Contributing / help wanted @ pydantic</b>: <a href=”https://github.com/samuelcolvin/pydantic/labels/help wanted” target=”_blank” rel=”noopener”>github.com</a><br/>
<b>python-devtools package</b>: <a href=”https://python-devtools.helpmanual.io/” target=”_blank” rel=”noopener”>python-devtools.helpmanual.io</a><br/>
<br/>
<b>IMPORTANT: PEP 563, PEP 649 and the later on of pydantic #2678</b><br/>
<b>GitHub issue on Typing</b>: <a href=”https://github.com/samuelcolvin/pydantic/issues/2678″ target=”_blank” rel=”noopener”>github.com</a><br/>
<br/>
<b>YouTube live stream video</b>: <a href=”https://www.youtube.com/watch?v=3S8QZeHCbAI” target=”_blank” rel=”noopener”>youtube.com</a><br/></div><br/>
<strong>Sponsors</strong><br/>
<br/>
<a href=’https://talkpython.fm/45drives’>45Drives</a><br>
<a href=’https://talkpython.fm/training’>Talk Python Training</a>

April 22, 2021 08:00 AM UTC


Codementor

TEST DJANGO APPS QUICKLY

Testing your Django using doesn’t have to be overwhelming!

April 22, 2021 02:20 AM UTC


Matthew Wright

Profiling Python lawmaking with memory_profiler

When your Python program uses increasingly memory than expected, you can use memory_profiler to find out where memory is allocated.

The post Profiling Python lawmaking with memory_profiler appeared first on wrighters.io.

April 22, 2021 01:03 AM UTC

April 21, 2021


Ching-Hwa Yu

How to Use pytest-mock to Simulate Responses

Use pytest-mock to simulate responsesWaiting for responses can be slow and time consuming…

One of the biggest challenges facing an electrical, computer, or diamond engineer is bridging the gap between hardware and software. The task to write software to exercise hardware has unchangingly proved to be a challenging task. This is primarily due to the focus on learning language syntax and not unbearable time spent on learning debugging and software testing. The gap widens remoter when asked to prove that the software isn’t introducing problems when exercising hardware. This typically leads to hours of long full system tests to ensure repeatability which is not a scalable solution when hardware is involved due to slow responses. For Python developers, the solution is to write unit tests of the test lawmaking using pytest and the pytest-mock plugin to simulate hardware responses.

The lawmaking in this vendible is misogynist at https://github.com/chinghwayu/mock_tutorial.

NOTE: While this post is written for the hardware engineer, this concept moreover extends to any external process or system such as a database.

Mock Objects

At the liaison layer, there is typically lawmaking to interact with hardware (or external system). This “driver” is usually coded as a matriculation with methods. A suburbanite will typically include low level functions such as initialize, send, read, and close. Higher level functions include methods such as set mode, configure output, capture data, program, and many others. In this interaction, there are a couple of items to check:

  • Are commands stuff properly constructed? The writ itself may be dynamically generated and have variations depending on input parameters.
  • Are responses stuff properly consumed? The raw response may have some data post-processing that requires validation.

In these cases, a mock object can be created to simulate the hardware. The mock object can return the writ that was sent and returns pre-programmed responses in a short value of time. This is an important goody as in many cases, hardware responses can be slow.

pytest and pytest-mock

While tests can be written in many variegated ways, pytest is the most popular Python test runner and can be extended through the use of plugins. pytest-mock is a plugin library that provides a pytest fixture that is a thin wrapper virtually mock that is part of the standard library. This post will discuss using the pytest-mock plugin to create mock objects to simulate responses.

Driver code

from time import sleep
from fabric import Connection

class Driver:
    def __init__(self, hostname):
        self.connection = Connection(hostname)

    def run(self, command):
        sleep(5)
        return self.connection.run(command, hide=True).stdout.strip()

    def disk_free(self):
        return self.run("df -h")

    @staticmethod
    def extract_percent(output):
        free_line = output.split("n")[1]
        percent = free_line.split()[4]
        return percent

The suburbanite whilom is a simple example. It uses a library tabbed Fabric to establish an SSH connection. There are two methods:

  1. run() – Allows any generic writ to be issued on the target and returns the raw output. Surpassing the output is returned, a five second wait is inserted to simulate a slow response.
  2. disk_free() – Generates a writ “df -h” and then calls the run() method with the generated command
  3. extract_percent() – Parses the raw output and returns the disk self-ruling percent

Test Lawmaking in Integrated Style

import socket
from mock_tutorial.driver import Driver

def test_driver_integrated():
    d = Driver(socket.gethostname())
    result = d.disk_free()
    percent = d.extract_percent(result)
    predicate percent == "75%"

The whilom test lawmaking is typically written in a woebegone box testing style to test this driver. First, the suburbanite object is instantiated, the disk_free() function is called, the output is parsed, and then finally compared with an expected result.

$ pytest -s
========================= test session starts ========================
platform linux -- Python 3.9.4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: /home/chinghwa/projects/mock_tutorial
plugins: mock-3.5.1
collected 1 item

tests/test_driver.py .                                          [100%]
========================== 1 passed in 5.51s =========================

In wing to the slow execution of 5.51 seconds, there is flipside problem. The output of “df -h” will most likely transpiration over time and not stay at 75%. While this example is contrived, it illustrates the need for the output to checked in flipside way.

Test Lawmaking with pytest-mock to Simulate Response

import socket
import pytest
from mock_tutorial.driver import Driver

def test_driver_unit(mocker):
    output_list = [
        "Filesystem      Size  Used Avail Use% Mounted on",
        "rootfs          472G  128G  344G  28% /",
        "none            472G  128G  344G  28% /dev",
    ]
    output = "n".join(output_list)
    mock_run = mocker.patch(
        "mock_tutorial.driver.Driver.run", return_value=output
    )
    d = Driver(socket.gethostname())
    result = d.disk_free()
    percent = d.extract_percent(result)
    mock_run.assert_called_with("df -h")
    predicate percent == "28%"

The whilom lawmaking was rewritten to use a mock object to patch (replace) the run() method. First, we need to import pytest (line 2) and undeniability the mocker fixture from pytest-mock (line 5).

On lines 12-14, the run() method of the Driver matriculation was patched with a pre-programmed response to simulate an very response. This ways that any undeniability to run() will return the string value of output.

Line 18 will trammels the writ that was sent to the run() method. When the disk_free() method is called, this will generate a writ of “df -h” and undeniability run() with this command.

Line 19 will trammels the parsing functions that extracts the percent from output. If the Use% in line 8 is changed, this will goof as this is the value that is stuff extracted.

$ pytest -s
========================= test session starts ========================
platform linux -- Python 3.9.4, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: /home/chinghwa/projects/mock_tutorial
plugins: mock-3.5.1
collected 1 item

tests/test_driver.py .                                          [100%]
========================== 1 passed in 0.36s =========================

After the mock objects have been added, the test time is reduced to 0.36 seconds. The slow run() method was patched to execute faster and moreover the lawmaking to parse the simulated output was checked.

Summary and Resources

This should provide a good starting point for developing fast performing unit tests in Python by patching slow response with mock objects. In wing to unit tests, integration tests should moreover be written however they can be executed less frequently.

This post is the first I’ve written on this topic in Python and I hope to delve into other pytest-mock methods in the future.

For spare information:

The post How to Use pytest-mock to Simulate Responses appeared first on Ching-Hwa Yu.

April 21, 2021 05:00 PM UTC


Python Morsels

4 ways to import a module in Python


image

Transcript

Let’s talk well-nigh the four ways to import something from a module in Python.

Importing the whole module object

The first way is to use the import statement, using the syntax import module_name:

>>> import math

We’ve just imported the math module.
We can use the things within this module by looking up nature on the math module object.
For example we can get the square root of a number by calling math.sqrt:

>>> math.sqrt(25)
5.0

Or we can wangle the number π with math.pi:

>>> math.pi
3.141592653589793

But we can’t wangle just pi or sqrt (without that math. prefix):

>>> pi
Traceback (most recent undeniability last):
  File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
>>> sqrt(25)
Traceback (most recent undeniability last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
>>>

The reason is, when we import a module using that import module_name syntax, we get just one thing: a variable that points to a module object.

>>> import math
>>> math
<module 'math' (built-in)>

Everything in that module is wieldy as an attribute on that module object:

>>> math.pi
3.141592653589793

Importing explicit things from a module

If you wanted to just type pi instead of math.pi, you could use the from syntax for importing:

>>> from math import pi
>>> pi
3.141592653589793

So now we have pi, but not sqrt (because we didn’t import it):

>>> sqrt(25)
Traceback (most recent undeniability last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined

And we don’t have wangle to the whole math module:

>>> math
Traceback (most recent undeniability last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined

If you want to import multiple things from a module using this from syntax, you could put commas each thing you’d like to import:

>>> from math import pi, sqrt
>>> pi
3.141592653589793
>>> sqrt(25)
5.0

That from math import pi, sqrt line plucks out pi and sqrt from the math module, but nothing else.

Avoiding name standoff when importing

If you use the from syntax to grab explicit things from a module and you grab something of the same name from two variegated modules, you’re in for trouble.

Here we’re importing sqrt from the math module and sqrt from the cmath module (cmath is for ramified numbers):

>>> from math import sqrt
>>> from cmath import sqrt

The sqrt function we end up with came from the cmath module:

>>> sqrt(25)
(5 0j)

We imported two variegated functions named sqrt and the last one won.
We first got sqrt from the math module and then we overwrote our local sqrt variable with the sqrt function from the cmath module.

To fix this we could rename sqrt from the cmath module as we import it, by using the as syntax:

>>> from math import sqrt
>>> from cmath import sqrt as csqrt

So, sqrt is now the sqrt function from the math module and csqrt is the one from the cmath module:

>>> sqrt(25)
5.0
>>> csqrt(25)
(5 0j)

If you squint at the the function the csqrt variable points to, you’ll plane see that it’s unquestionably tabbed sqrt:

>>> csqrt
<built-in function sqrt>

We pointed our local variable csqrt to the sqrt function within the cmath module.

Importing a module under a variegated name

You can moreover use the as syntax when importing a whole module.

>>> import math as m

The variable m now points to the math module object which ways we can’t say math.pi anymore:

>>> math.pi
Traceback (most recent undeniability last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined

Instead we can use m.pi or m.sqrt:

>>> m.pi
3.141592653589793
>>> m.sqrt(25)
5.0

You likely won’t see this institute used often except in explicit Python communities where it’s commonplace.

For example, in the Pandas world people often import pandas as pd:

>> import pandas as pd

And in the NumPy world, people often import numpy as np:

import numpy as np

It’s not very worldwide to see module names shortened using the as syntax, except in areas where it’s conventional (like Pandas and NumPy).

Trey says: If I saw m.pi in your code, I’d probably find it a little bit odd.

The 4 ways to import a module

So there’s four variegated ways to import:

  1. Import the whole module using its original name:
    pycon
    import random
  2. Import explicit things from the module:
    pycon
    from random import choice, randint
  3. Import the whole module and rename it, usually using a shorter variable name:
    pycon
    import pandas as pd
  4. Import explicit things from the module and rename them as you’re importing them:
    pycon
    from os.path import join as join_path

That last one is usually washed-up to stave a name standoff or sometimes to make a increasingly descriptive name (though that’s not very common).

Trey’s recommendations

  1. Use from for short and descriptive variable names
    I tend to use the from syntax most (number 2 above) considering I prefer short and descriptive variable names.

  2. Import the whole module if needed to stave ambiguity.
    If there’s a name like choice that isn’t as well-spoken as random.choice, then I prefer to import the whole module for a increasingly descriptive name

  3. Avoid renaming imports.
    I very rarely use the as syntax (unless I’m in the pandas or numpy worlds, where it’s worldwide convention).
    And I scrutinizingly never use the as syntax with from unless I’m lamister a name collision.

April 21, 2021 03:00 PM UTC


Real Python

Python Polity Interview With Moshe Zadka

This week, I’m joined by Moshe Zadka, a senior site reliability engineer at SurveyMonkey. Moshe is a cadre developer for the Twisted framework and a Real Python author.

In this interview, we discuss a variety of topics, including the Twisted framework, Python for DevOps, writing Python books, and tai chi.

Ricky: Thanks for joining me, Moshe. I’d like to start with the same questions I do with all my interview guests: how did you get into programming, and when did you start using Python?

Moshe Zadka

Moshe: The first programming project I remember working on was a project for class, converting numbers from decimal to binary in Basic. The teacher thought this was a little wide for a seven-year-old, which was my main motivation for finishing it.


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

April 21, 2021 02:00 PM UTC

Comments are closed.