How to : What are python class variables ?

In Python we have class variables, they are not defined in any methods. They are defined at class level. The only advantage of a class variable is it stays with class. If you instantiate your class and created an object, still with object you can access the class_variable.

In [1]: class A(object):
   ...:     class_var = 10
   ...:     def __init__(self):
   ...:         A.class_var = 20
   ...: 

In [2]: a = A()

In [3]: a.class_var
Out[3]: 20

In [4]: A.class_var
Out[4]: 20
But if you use self and defined another variable with same name, then you will have two variables. You can still access using class and another you can access using your new object.

In [5]: class B(object):
   ...:     class_var = 10
   ...:     def __init__(self):
   ...:         self.class_var = 40
   ...: 

In [6]: b = B()

In [8]: b.class_var
Out[8]: 40

In [9]: B().class_var
Out[9]: 40

In [10]: B.class_var
Out[10]: 10

In [11]: 
  
The sample code and outputs, hope they will help you understand their flow. Thank you. Raja G

Python: How to print a json object in table format

If you have json object and you want print the json object in table format, then you are the right place. Though I didn't wrote any module, I found one which can help. There is a module named pytablewriter. You can use that module to print your json object in many formats, checkout their documenration for more information. Now let's get into business. Lets say you have a json object like below
obj = [{
	'name': 
	'Fix PRB', 
	'project': 
	'PRB', 
	'status': 
	'New', 
	'category': 
	'work', 
	'created_on': 
	'2021-05-13 19:29:39.023231'}, {
	'name': 
	'catalog_broken', 
	'project':  
	'zoom', 
	'status': 
	'New', 
	'category': 
	'work', 
	'created_on': 
	'2021-05-13 19:54:42.109463'}]
We need to build couple of parameters first. Create 3 variables with names as table_name, headers, value_matrix.
table_name = 
	"Todo List"
	# this will not print, its just needed.
headers = []
value_matrix = []
Now lets extract keys and values from given json object.
headers = list(obj[
	0].keys())


	for item 
	in obj:
	value_matrix.append(list(item.values()))
So we built the needed data, now lets print it.
	from pytablewriter 
	import UnicodeTableWriter
writer = UnicodeTableWriter( table_name = table_name, headers = headers, value_matrix = value_matrix )
writer.write_table()
┌──────────────┬───────┬──────┬────────┬──────────────────────────┐
│     name     │project│status│category│        created_on        │
├──────────────┼───────┼──────┼────────┼──────────────────────────┤
│Fix PRB       │PRB    │New   │work    │
	2021
	-05
	-13
	19:
	29:
├──────────────┼───────┼──────┼────────┼──────────────────────────┤
│catalog_broken│zoom   │New   │work    │
	2021
	-05
	-13
	19:
	54:
└──────────────┴───────┴──────┴────────┴──────────────────────────┘
And that's it. It will create a table with give json object. Check the pytablewriter documentation for more options. So I have created a fucntion which you use if you needed in case
	
		def
		pyTablePrinter
		(json_obj, table_name=
			"Todo List")
		:
	

        table_name = table_name
        headers = []
        value_matrix = [] 

        headers = list(json_obj[
	0].keys())
        
	for item 
	in json_obj :
            value_matrix.append(list(item.values()))
        
        writer = UnicodeTableWriter( table_name = table_name, headers = headers, value_matrix = value_matrix )
        writer.write_table()

Hope it helps. Thank you Raja G

Python: Absolute Imports

In Python, Absolute imports can be done in 3 ways. Let's say we have a project structure as below























Let's say you have so many classes and functions inside the products module then we can go with the below syntax.

        
            
            from ecommerce import products
            product = products.Product()
        
    


If we have only one or two classes then we can use the below syntax.

        
  			from ecommerce.products import Product
			product = Product()
		

The last method is very rarely used and I don't see anywhere it's being used, but it's good to know for a specific use case. Let's say you have two but different modules named products and if you want to import both of them, if you follow any of the above methods, for sure you will get name conflict issues. To avoid that you can follow the below syntax

        
  	import ecommerce.products
	product = ecommenrce.products.Product()
    
    

Hope that helps.
Raja


How to create containerized Python development environment using Dockers ?

Hello Everyone, In this article, I will demonstrate how to create your Docker based Python runtime environment. Assume you’re in the folder where you have your python code in a file named main.py and requirements.txt Lets first build our Python container with this setup. With your favorite editor, open a file named pyDockerfile, lets go with custom names instead of default Dockerfile, It would be easy to manage. But its your choice, I am going with pyDockerfile And add below code

FROM python:3.6
RUN mkdir /app
WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY main.py .

ENTRYPOINT ["python"]
CMD ["main.py"]
We are downloading/pulling Python3.6 image creating /app directory inside the container switching context or as current working directory to /app copy the requirements.txt file install the requirements with pip copy main source code, which is in main.py in my case Adding entrypoint as python so strictly my container will accept python based arguments. and executing my code in main.py In your host machine lets create a sample requirements.txt file as

requests
And main.py

import requests
url = {
"google": "https://google.com",
"azure" : "https://portal.azure.com"
}
for item in url :
req = requests.get(url[item])
print(f"{item}", req.status_code)
Now lets build our image

$ docker build -t pyrunner -f pyDockerfile .
adding tag to our image as pyrunner as I have used custom name for dockerfile pyDockerfile once image created lats verify

docker image list
# or
docker images
Verify output of our images by running

docker container run --rm -it pyrunner
You should see output as

google 200
azure 200
Lets modify our code in main.py as

import requests

url = {
    "facebook": "https://facebook.com",
    "google": "https://google.com",
    "azure" : "https://portal.azure.com"
}

for item in url :
    req = requests.get(url[item])
    print(f"{item}", req.status_code)

We have added a new URL for facebook. Lets start a container with command as below

 docker container run --rm -it -v $(pwd):/app pyrunner
 

--rm : this is delete the container immediately after execution completed. -v we are using volume concept and mounting the current directory where we havemain.py and requirements.txt file and mounting at /app mount point in the remote directory. and you should seeing the output as below

facebook 200
google 200
azure 200
so as you have seen we have done changes to our code and our container adopted that automatically in its next execution.