analitics

Pages

Showing posts with label 3.9. Show all posts
Showing posts with label 3.9. Show all posts

Tuesday, May 18, 2021

Python 3.9.1 : ABC - Abstract Base Classes - part 001.

Abstract classes are classes that contain one or more abstract methods.
By default, Python does not provide abstract classes.
Python comes with a module that provides the base for defining Abstract Base Classes (named ABC).
An abstract class can be considered as a blueprint for other classes.
By defining an abstract base class, you can define a common API for a set of subclasses.
A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.
[mythcat@desk ~]$ python3.9
Python 3.9.5 (default, May  4 2021, 00:00:00) 
[GCC 10.3.1 20210422 (Red Hat 10.3.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from abc import ABC
>>> class Test_ABC(ABC):
...     pass
... 
>>> Test_ABC.register(tuple)

>>> assert issubclass(tuple,Test_ABC)
>>> assert isinstance((), Test_ABC)
>>> class Foo:
...     def __getitem__(self, index):
...         ...
...     def __len__(self):
...         ...
...     def get_iterator(self):
...         return iter(self)
... 
>>> Test_ABC.register(Foo)
...
Let's see an example:
from abc import ABC, abstractmethod
 
class Vehicle(ABC):
    @abstractmethod
    def action(self):
        pass

class Air(Vehicle):
    # overriding abstract method
    def action(self):
        print("this flies in the air")
 
class Ground(Vehicle):
    # overriding abstract method
    def action(self):
        print("this running on the field")

class Civil(Ground):
    def action(self):
        print("Civil class - running on the field")

# Can't instantiate abstract class with abstract method action, don't use it
# abc = Vehicle()

abc = Air()
abc.action()

abc = Ground()
abc.action()

abc = Civil()
abc.action()

print( issubclass(Civil, Vehicle))
print( isinstance(Civil(), Vehicle))
This is the result:
[mythcat@desk PythonProjects]$ python3.9 ABC_001.py 
this flies in the air
this running on the field
Civil class - running on the field
True
True

Thursday, February 25, 2021

Python 3.9.1 : Python and Spectator Earth.

The Spectator Earth allows you to track satellites, access their imagery, and easily build new information, based on data from this amazing orbital infrastructure.
You need just an API KEY to use it with cURL, Python, or JavaScript. 
In this tutorial, I will show you how can be used.
Login on the app.spectator.earth and get your API Key. 
Let's see some simple examples.
This first example shows you the satellite by id:
import requests

id = input("Type id sattelite: ")
satellite_id = id
url = 'https://api.spectator.earth/satellite/{satellite_id}'.format(satellite_id=satellite_id)

response = requests.get(url)
data = response.json()
print(data)
Let's see some satellite by ids:
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 1
{'id': 1, 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-51.88851761326367, 
70.75978200389422]}, 'properties': {'name': 'Sentinel-1A', 'norad_id': 39634, 'sensors': 
[{'type': 'SAR', 'avg_footprint_width': '3.20'}], 'open': True, 'platform': 'Sentinel-1A'}}
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 2
{'id': 2, 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [42.046601163641796, 
-14.660442921557335]}, 'properties': {'name': 'Sentinel-2A', 'norad_id': 40697, 'sensors': 
[{'type': 'OPTICAL', 'avg_footprint_width': '2.32'}], 'open': True, 'platform': 'Sentinel-2A'}}
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 3
{'id': 3, 'type': 'Feature', 'geometry': {'type': 'Point', 'coordinates': [-91.98478583784988, 
79.45732380441011]}, 'properties': {'name': 'Sentinel-3A', 'norad_id': 41335, 'sensors': 
[{'type': 'OPTICAL', 'avg_footprint_width': '10.16'}, {'type': 'OPTICAL', 
'avg_footprint_width': '11.20'}], 'open': True, 'platform': 'Sentinel-3A'}}
[mythcat@desk Spectator]$ python  satellite_all.py 
Type id sattelite: 4
Let's see one example with satellite overpasses:
import requests
import json
api_key = input("api_key :")
bbox = '19.59,49.90,20.33,50.21'
satellites = 'Sentinel-2A,Sentinel-2B'
url = 'https://api.spectator.earth/overpass/?api_key={api_key}&bbox={bbox}&
satellites={satellites}'.format(api_key=api_key, bbox=bbox, satellites=satellites)
response = requests.get(url)
data = response.json()
print(type(data))
print(data)
You can query for overpasses of the chosen satellite over a defined area of interest and the output provides you with a satellite sensor footprint for the nearest overpass, overpass frequency in seconds, and all information available.
Query parameters for the URL variable are:
The result is this:
[mythcat@desk Spectator]$ python satellite.py 
api_key :....
...
{'frequency': 93996, 'overpasses': [{'id': 16486437, 'acquisition': True, 'date': 
'2021-02-26T09:57:00Z', 'footprint': {'type': 'Polygon', 'coordinates': 
...
footprint': {'type': 'Polygon', 'coordinates': 
...
[[[19.153675312697636, 46.847554078717884], ... 
Query parameters for the url :
  • api_key - your API key
  • bbox - area of interest bounding box list of coords (lon, lat, lon, lat);
  • satellites - which satellites to include like: (Sentinel-1A, Sentinel-1A, Sentinel-2A, Sentinel-2B, Sentinel-3A, Landsat-8) - optional;
  • days_before - a number of days before the current date for which overpasses should be computed integer optional, default=0;
  • days_after - a number of days after the current date for which overpasses should be computed integer optional, default=7;
You can see a image get from my location:

Saturday, October 10, 2020

Python 3.9.0 : Union and in-place union operators

Python introduces two new operators for dictionaries named union used in code with pipe operator | and in-place union used in python code with this |=.

I this tutorial I will show you how can be used:
[mythcat@desk ~]$ python3.9 
Python 3.9.0 (default, Oct  6 2020, 00:00:00) 
[GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> step_one = {"worker_one":"task_one", "worker_two":"task_two"}
>>> step_two = {"worker_three":"task_one", "worker_fouw":"task_two"}
>>> merged_step_one_step_two = {**step_one, **step_two}
>>> empty = {}
>>> empty |= step_one
>>> empty
{'worker_one': 'task_one', 'worker_two': 'task_two'}
>>> step_one 
{'worker_one': 'task_one', 'worker_two': 'task_two'}
>>> step_two
{'worker_three': 'task_one', 'worker_fouw': 'task_two'}
>>> all = step_one | step_two 
>>> all 
{'worker_one': 'task_one', 'worker_two': 'task_two', 'worker_three': 'task_one', 'worker_fouw': 'task_two'} 
>>> copy_step_one = empty | step_one
>>> copy_step_one 
{'worker_one': 'task_one', 'worker_two': 'task_two'} 
>>> copy_step_one |= [("manager", "steps")]
>>> copy_step_one 
{'worker_one': 'task_one', 'worker_two': 'task_two', 'manager': 'steps'}
You can easily see how to use these operators with the dictionaries created and how to add lists to dictionaries. Operations with these operators always result in a dictionary. The order of these operations is important, see example:
>>> numbers = {0: "zero", 1: "one"}
>>> numbers_one = {0: "zero", 1: "one"}
>>> numbers_two = {0: "zero", 2: "two"}
>>> numbers_one | numbers_two
{0: 'zero', 1: 'one', 2: 'two'}
>>> numbers_two | numbers_one
{0: 'zero', 2: 'two', 1: 'one'}
>>> numbers_three = {0: 'zero', 11: 'error 1', 22: 'error 2', 33:'error 3'}
>>> numbers_three | numbers_one
{0: 'zero', 11: 'error 1', 22: 'error 2', 33: 'error 3', 1: 'one'}
>>> numbers_one | numbers_three
{0: 'zero', 1: 'one', 11: 'error 1', 22: 'error 2', 33: 'error 3'}
You can see how the dictionaries are overwritten by the union operation. These operations are implemented through dunder operations for most the dictionary objects except abstract classes. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. You can find on this page.

Python 3.9.0 : Introduction to release 3.9.0.

This is a short introduction to release 3.9.0. 
Five days ago, a new release of version 3.9 appeared with a series of improvements and new python packages, see the official website
You can install easily on Fedora 32 with dnf tool.
[root@desk mythcat]# dnf install  python39.x86_64
...
Installing:
 python39                x86_64                3.9.0-1.fc32
...
Installed:
  python39-3.9.0-1.fc32.x86_64                                                                             

Complete!
A new article written about this release shows some of the advantages of this programming language, you can read it here
You can run easily with this command;
[root@desk mythcat]# python3.9
Python 3.9.0 (default, Oct  6 2020, 00:00:00) 
[GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information. 
You can configure python with this command, see an example:
[root@desk mythcat]# python3.9-x86_64-config --libs 
 -lcrypt -lpthread -ldl  -lutil -lm -lm 
This release of Python 3.9 uses a new parser, based on parsing expression grammar (PEG) instead of LL(1) know as LL parser (Left-to-right, Leftmost derivation). PEG parsers are more powerful than LL(1) parsers and avoid the need for special hacks. This the same abstract syntax tree (AST) as the old LL(1) parser. The PEG parser is the default, but you can run your program using the old parser, see the next example:
[mythcat@desk ~]$ python3.9 -X oldparser my_script_name.py
...
One of the most important improvements for me is PEP 614 -- Relaxing Grammar Restrictions On Decorators. In Python 3.9, these restrictions are lifted and you can now use any expression. 
For example including one accessing items in a dictionary, like this simple example:

buttons = {
  "hello": QPushButton("hello word!"),
  "bye": QPushButton("bye word!"),
  "buy": QPushButton("buy!!"),
}
...
@buttons["hello"].clicked.connect
def speak_hello():
... 
Yes, comes with another Python Enhancement Proposals - PEP 615 with support for the IANA Time Zone Database in the Standard Library. This acronym is similar to I.A.N.A known as the Internet Assigned Numbers Authority, but it is not the same. 
In this case, the zoneinfo module provides a concrete time zone implementation to support the IANA time zone database. 
This support contains code and data that represent the history of local time for many representative locations around the globe. Many features for math, strings, union operator for the dictionary, HTTP codes, and more. 
Completion of variable and module names is automatically enabled at interpreter startup so that the Tab key invokes the completion function. 
You can see a simple example with zoneinfo python module and completion feature.
[mythcat@desk ~]$ python3.9
Python 3.9.0 (default, Oct  6 2020, 00:00:00) 
[GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from zoneinfo import ZoneInfo
>>> import zoneinfo
>>> zoneinfo.available_timezones()
{'Hongkong', 'America/Iqaluit', 'America/Indianapolis', 'America/Louisville', 'America/New_York', 
'America/Mazatlan', 'Australia/Yancowinna', 'Africa/Ndjamena', 'Portugal', 'Africa/Bujumbura', 
'America/Rosario', 'America/Antigua','America/Indiana/Tell_City', 'America/Managua', 
'Europe/Paris', 'Europe/Oslo', 
...
>>> tz = ZoneInfo("Europe/Bucharest")
>>> tz.
tz.clear_cache(  tz.from_file(    tz.key           tz.tzname(       
tz.dst(          tz.fromutc(      tz.no_cache(     tz.utcoffset(    
>>> tz. 
On my desktop I got this result:
[mythcat@desk ~]$ python var_access_benchmark.py 
Variable and attribute read access:
   6.0 ns	read_local
   6.5 ns	read_nonlocal
  10.7 ns	read_global
  10.7 ns	read_builtin
  25.2 ns	read_classvar_from_class
  23.4 ns	read_classvar_from_instance
  34.3 ns	read_instancevar
  29.4 ns	read_instancevar_slots
  26.8 ns	read_namedtuple
  42.4 ns	read_boundmethod

Variable and attribute write access:
   6.6 ns	write_local
   7.0 ns	write_nonlocal
  23.3 ns	write_global
  54.1 ns	write_classvar
  46.4 ns	write_instancevar
  39.4 ns	write_instancevar_slots

Data structure read access:
  26.1 ns	read_list
  28.1 ns	read_deque
  27.5 ns	read_dict
  25.8 ns	read_strdict

Data structure write access:
  29.6 ns	write_list
  31.7 ns	write_deque
  34.4 ns	write_dict
  31.7 ns	write_strdict

Stack (or queue) operations:
  55.5 ns	list_append_pop
  49.7 ns	deque_append_pop
  51.0 ns	deque_append_popleft

Timing loop overhead:
   0.4 ns	loop_overhead