SlideShare a Scribd company logo
4
Most read
5
Most read
15
Most read
Python for Delphi
Developers (Part II)
Webinar by Kiriakos Vlahos (aka PyScripter)
and Jim McKeeth (Embarcadero)
Contents
•VarPyth
Using python libraries and objects in Delphi code
•Core libraries
•Visualization
•Machine Learning
Python based data analytics in Delphi applications
•TPythonThread
Running python scripts without blocking your GUI
Creating Python extension modules using Delphi
•WrapDelphi and WrapDelphiVCL units
Python GUI development using the VCL
VarPyth
• High-level access to python objects from Delphi code
• It also allows you to create common python objects (lists, tuples etc.)
• Uses custom variants
• No need to use the low-level python API or deal with python object reference
counting
• Small performance penalty
• Example
• ShowMessage(SysModule.version)
• Explore Demo25 and the VarPyth unit tests
VarPyth Demoprocedure TForm1.FormCreate(Sender: TObject);
begin
var np := Import('numpy');
var np_array: Variant :=
np.array(VarPythonCreate([1,2,3,4,5,6,7,8,9,10]));
PythonModule.SetVar('np_array’,
ExtractPythonObjectFrom(np_array));
end;
Python code:
from delphi_module import np_array
print("type(np_array) = ", type(np_array))
print("len(np_array) = ", len(np_array))
print("np_array = ", np_array)
res_array = np_array.copy()
for i in range(len(np_array)):
res_array[i] *= np_array[i]
print("res_array = ", res_array)
Output:
type(np_array) = <class 'numpy.ndarray'>
len(np_array) = 10
np_array = [ 1 2 3 4 5 6 7 8 9 10]
res_array = [ 1 4 9 16 25 36 49 64 81 100]
procedure TForm1.btnRunClick(Sender: TObject);
begin
GetPythonEngine.ExecString(UTF8Encode(sePythonCode.Text));
for var V in VarPyIterate(MainModule.res_array) do
ListBox.Items.Add(V);
end;
To learn more, explore Demo25 and the VarPyth unit tests
Core Python Libraries
• Core libraries
• numpy – arrays and matrix algebra
• scipy – math, science and engineering
• pandas – data structure and analysis, R-like dataframes
• Data visualization
• matplotlib – matlab-like plotting
• seaborn – statistical data visualization
• mpld3 – turn matplotlib plots into interactive web pages
• bokeh - interactive visualization library for modern browsers
• plotly – interactive browser-based graphing library
• altair – based on the visualization grammar vega-light
Data visualization
Demos - pyVIZsvg
• Create charts with python
libraries, save them in svg
format and plot them in Delphi
• Uses matplotlib and seaborn
python libraries
• Uses TSVGIconImage from
EtheaDev SVGIconImageList
components
Interactive Data
Visualization Demo -
PychartHtml
• Create interactive charts in
python save them to html and
show them inside Delphi
applications
• Showcases the new
TEdgeBrowser
• Uses the matplotlib with mpld3,
altair and bohek python
libraries
Machine Learning Python Libraries
• tensorflow (Google)
• keras – high level pythonic interface
• PyTorch (Facebook)
• CNTK - The Microsoft Cognitive Toolkit (Microsoft)
• Spark MLlib and mxnet (Apache Foundation)
• scikit-learn
• pure-python, general library, wide coverage, good choice for newcomers to
ML/AI
Data Analytics Demo:
COVID-19
• Demonstrates the combined use of numpy,
pandas, matplotlib and scikit-learn
• Use pandas to download Covid-19 confirmed
cases data from Web and aggregate it
• Use scikit-learn to
• Split the data into training and test sets
• Transform the data
• Define model (Bayesian Ridge Regression)
• Optimize model parameters
• Generate predictions
• Use matplotlib to compare actual vrs fitted test
data.
Running Python Scripts Without
Blocking Your Main Thread
• Python uses the infamous Global Interpreter Lock (GIL)
• This means that only one thread can run python code at any given time
• Python switches between python created threads automatically
• Applications using python need to acquire the GIL before running python
code and release it soon afterwards
• Welcome to TPythonThread
• TThread descendent
• Automatically acquires and releases the GIL
Python threads –
demo33
• Shows you how to
• use TPythonThread
• use new sub-interpreters
• synchronize with the main
thread
• interrupt running threads
with a keyboard interrupt
exception
Technical Aside I
• FPU Exception mask
• Delphi’s default FPU exception mask is different from most other Windows apps
• Incompatible with python libraries written in C or C++
• If you use numpy, scipy, tensorflow etc. you need to match the FPU mask they
expect to operate with
• PythonEngine.pas provides a function for doing that: MaskFPUExceptions
• Call MaskFPUExceptions(True) before python is loaded
• e.g. the initialization section of your main form
• See the P4D Wiki page for details
Technical Aside II
• Working with different python distributions:
• P4D makes a good effort to discover registered python distributions automatically
• But sometimes you want to use python distributions which are not registered
• One such case is when want to deploy your application bundled with python.
Python.org offers such a minimal distribution for applications embedding python.
• Additional considerations apply when using an Anaconda distribution
• Read the Finding Python P4D Wiki page carefully
P4D Python Extension Modules
• Python extension modules are dynamic link libraries that can be used by
python in a way similar to modules developed in python.
• They have ‘pyd’ extension.
• P4D makes it very easy to create extension modules that contain functions
and types developed in Delphi.
• These extension modules can be used by Python, independently of Delphi,
and can be packaged with setuptools and distributed through PyPi.
Python extension modules Demo
function PyInit_DemoModule: PPyObject;
//function exported by dll – initializes the module
begin
try
gEngine := TPythonEngine.Create(nil);
gEngine.AutoFinalize := False;
gEngine.UseLastKnownVersion := False;
// Adapt to the desired python version
gEngine.RegVersion := '3.8';
gEngine.DllName := 'python38.dll';
gModule := TPythonModule.Create(nil);
gModule.Engine := gEngine;
gModule.ModuleName := 'DemoModule';
gModule.AddMethod('is_prime', delphi_is_prime,
'is_prime(n) -> bool' );
gEngine.LoadDll;
except
end;
Result := gModule.Module;
end;
Python test module: test.py
from DemoModule import is_prime
from timeit import Timer
def count_primes(max_n):
res = 0
for i in range(2, max_n + 1):
if is_prime(i):
res += 1
return res
Command line:
> C:PythonPython38python test.py
Number of primes between 0 and 1000000 = 78498
Elapsed time: 0.29756570000000004 secs
Wrapping VCL as a Python
Extension Module I
• We can use the same approach to create an extension module wrapping
VCL
• Uses the WrapDelphi and WrapDelphiVCL units
• The whole of VCL (almost) is wrapped in 40 lines of code
• The generated Delphi.pyd file is only 5Mbs
• It can be uses to create VCL-based GUIs in python without needing Delphi
• A similar approach could be used to wrap FMX and create a multi-platform
python GUI library
• Unclear whether there are licensing restrictions in distributing such a file
Wrapping VCL as a Python
Extension Module II
unit uMain;
interface
uses PythonEngine;
function PyInit_Delphi: PPyObject; cdecl;
implementation
uses WrapDelphi, WrapDelphiVCL;
// similar to the previous extension module
TestApp.py
from Delphi import *
class MainForm(Form):
def __init__(self, Owner):
self.Caption = "A Delphi Form..."
self.SetBounds(10, 10, 500, 400)
self.lblHello = Label(self)
self.lblHello.SetProps(Parent=self, Caption="Hello World")
self.lblHello.SetBounds(10, 10, 300, 24)
self.OnClose = self.MainFormClose
def MainFormClose(self, Sender, Action):
Action.Value = caFree
def main():
Application.Initialize()
Application.Title = "MyDelphiApp"
f = MainForm(Application)
f.Show()
FreeConsole()
Application.Run()
main()
Command line:
> C:PythonPython38python .TestApp.py
Summary
• With Python for Delphi you can get the best of both worlds
• P4D makes it very easy to integrate Python into Delphi applications in RAD
way, thus providing access to a vast range of python libraries
• Expose Delphi function, objects, records and types to Python using low or
high-level interfaces (WrapDelphi)
• Create/Access/Use Python objects/modules in your Delphi code using a high-
level interface (VarPyth)
• Run python code in threads
• Create python extensions modules
• Wrap Vcl as a Python extension module to create GUIs with python
github.com/pyscripter/python4delphi/tree/master/Tutorials/Webinar%20II

More Related Content

What's hot (20)

PDF
OOP Review - Ôn tập Hướng Đối Tượng
Nguyễn Quang Thiện
 
DOCX
Suy diễn tiến
Súng Hoa
 
PPTX
Data mining - Luật kết hợp và ứng dụng
Phien Le
 
PPT
Bài giảng cơ sở dữ liệu
trieulongweb
 
PPT
Quy hoạch động
Hoàng Chí Dũng
 
PPTX
Python presentation
gaganapponix
 
PDF
Luận văn: Nghiên cứu hệ thống rút tiền tự động ATM, HOT
Dịch vụ viết bài trọn gói ZALO: 0909232620
 
PDF
ToanRoirac
. .
 
PDF
Giáo trình nhập môn lập trình - Đặng Bình Phương
hazzthuan
 
DOC
KHAI PHÁ LUẬT KẾT HỢP CÁC MÔN HỌC CỦA SINH VIÊN
Vu Truong
 
PDF
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
thuhuynhphonegap
 
PPTX
Dapper
Suresh Loganatha
 
DOCX
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
The Nguyen Manh
 
PPTX
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Peter Hlavaty
 
PDF
Giao thức RPL
Tonachi Shika
 
PPTX
Injection on Steroids: Codeless code injection and 0-day techniques
enSilo
 
PDF
Python Workshop
Saket Choudhary
 
PPT
Bai02 he thong quan ly tap tin
Vũ Sang
 
PPT
Blowfish epod
Rizka Kenali IV
 
PPT
Giáo trình Phân tích và thiết kế giải thuật - CHAP 1
Nguyễn Công Hoàng
 
OOP Review - Ôn tập Hướng Đối Tượng
Nguyễn Quang Thiện
 
Suy diễn tiến
Súng Hoa
 
Data mining - Luật kết hợp và ứng dụng
Phien Le
 
Bài giảng cơ sở dữ liệu
trieulongweb
 
Quy hoạch động
Hoàng Chí Dũng
 
Python presentation
gaganapponix
 
Luận văn: Nghiên cứu hệ thống rút tiền tự động ATM, HOT
Dịch vụ viết bài trọn gói ZALO: 0909232620
 
ToanRoirac
. .
 
Giáo trình nhập môn lập trình - Đặng Bình Phương
hazzthuan
 
KHAI PHÁ LUẬT KẾT HỢP CÁC MÔN HỌC CỦA SINH VIÊN
Vu Truong
 
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
thuhuynhphonegap
 
[Báo cáo] Bài tập lớn Ngôn ngữ lập trình: Quản lý thư viện
The Nguyen Manh
 
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Peter Hlavaty
 
Giao thức RPL
Tonachi Shika
 
Injection on Steroids: Codeless code injection and 0-day techniques
enSilo
 
Python Workshop
Saket Choudhary
 
Bai02 he thong quan ly tap tin
Vũ Sang
 
Blowfish epod
Rizka Kenali IV
 
Giáo trình Phân tích và thiết kế giải thuật - CHAP 1
Nguyễn Công Hoàng
 

Similar to Python for Delphi Developers - Part 2 (20)

PDF
Python indroduction
FEG
 
PDF
EKON 25 Python4Delphi_mX4
Max Kleiner
 
PDF
Anaconda Python KNIME & Orange Installation
Girinath Pillai
 
PDF
Ekon 25 Python4Delphi_MX475
Max Kleiner
 
PPTX
PyCourse - Self driving python course
Eran Shlomo
 
PDF
Travis Oliphant "Python for Speed, Scale, and Science"
Fwdays
 
PDF
Development_C_Extension_with_Pybind11.pdf
Takayuki Suzuki
 
PPTX
Python Tutorial Part 2
Haitham El-Ghareeb
 
PDF
Using SWIG to Control, Prototype, and Debug C Programs with Python
David Beazley (Dabeaz LLC)
 
PDF
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Foundation
 
PPTX
Python for security professionals by katoh jeremiah [py con ng 2018]
jerrykatoh
 
PDF
PySide
OpenBossa
 
PDF
PyCon2022 - Building Python Extensions
Henry Schreiner
 
PDF
Interfacing C/C++ and Python with SWIG
David Beazley (Dabeaz LLC)
 
PPTX
Introduction to Jupyter notebook and MS Azure Machine Learning Studio
Muralidharan Deenathayalan
 
PPTX
Introduction to Jupyter notebook and MS Azure Machine Learning Studio
Muralidharan Deenathayalan
 
PDF
PyData Boston 2013
Travis Oliphant
 
PPTX
Inference Servers New Technology | Same Old Security Flaws
pratikamin7777
 
PDF
Python testing like a pro by Keith Yang
PYCON MY PLT
 
PPTX
Python-Yesterday Today Tomorrow(What's new?)
Mohan Arumugam
 
Python indroduction
FEG
 
EKON 25 Python4Delphi_mX4
Max Kleiner
 
Anaconda Python KNIME & Orange Installation
Girinath Pillai
 
Ekon 25 Python4Delphi_MX475
Max Kleiner
 
PyCourse - Self driving python course
Eran Shlomo
 
Travis Oliphant "Python for Speed, Scale, and Science"
Fwdays
 
Development_C_Extension_with_Pybind11.pdf
Takayuki Suzuki
 
Python Tutorial Part 2
Haitham El-Ghareeb
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
David Beazley (Dabeaz LLC)
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Foundation
 
Python for security professionals by katoh jeremiah [py con ng 2018]
jerrykatoh
 
PySide
OpenBossa
 
PyCon2022 - Building Python Extensions
Henry Schreiner
 
Interfacing C/C++ and Python with SWIG
David Beazley (Dabeaz LLC)
 
Introduction to Jupyter notebook and MS Azure Machine Learning Studio
Muralidharan Deenathayalan
 
Introduction to Jupyter notebook and MS Azure Machine Learning Studio
Muralidharan Deenathayalan
 
PyData Boston 2013
Travis Oliphant
 
Inference Servers New Technology | Same Old Security Flaws
pratikamin7777
 
Python testing like a pro by Keith Yang
PYCON MY PLT
 
Python-Yesterday Today Tomorrow(What's new?)
Mohan Arumugam
 
Ad

More from Embarcadero Technologies (20)

PDF
PyTorch for Delphi - Python Data Sciences Libraries.pdf
Embarcadero Technologies
 
PDF
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...
Embarcadero Technologies
 
PDF
Linux GUI Applications on Windows Subsystem for Linux
Embarcadero Technologies
 
PDF
Python on Android with Delphi FMX - The Cross Platform GUI Framework
Embarcadero Technologies
 
PDF
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
Embarcadero Technologies
 
PDF
FMXLinux Introduction - Delphi's FireMonkey for Linux
Embarcadero Technologies
 
PDF
RAD Industrial Automation, Labs, and Instrumentation
Embarcadero Technologies
 
PDF
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embarcadero Technologies
 
PDF
Rad Server Industry Template - Connected Nurses Station - Setup Document
Embarcadero Technologies
 
PPTX
TMS Google Mapping Components
Embarcadero Technologies
 
PDF
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinar
Embarcadero Technologies
 
PPTX
Useful C++ Features You Should be Using
Embarcadero Technologies
 
PPTX
Getting Started Building Mobile Applications for iOS and Android
Embarcadero Technologies
 
PPTX
Embarcadero RAD server Launch Webinar
Embarcadero Technologies
 
PPTX
ER/Studio 2016: Build a Business-Driven Data Architecture
Embarcadero Technologies
 
PPTX
The Secrets of SQL Server: Database Worst Practices
Embarcadero Technologies
 
PDF
Driving Business Value Through Agile Data Assets
Embarcadero Technologies
 
PDF
Troubleshooting Plan Changes with Query Store in SQL Server 2016
Embarcadero Technologies
 
PDF
Great Scott! Dealing with New Datatypes
Embarcadero Technologies
 
PDF
Agile, Automated, Aware: How to Model for Success
Embarcadero Technologies
 
PyTorch for Delphi - Python Data Sciences Libraries.pdf
Embarcadero Technologies
 
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...
Embarcadero Technologies
 
Linux GUI Applications on Windows Subsystem for Linux
Embarcadero Technologies
 
Python on Android with Delphi FMX - The Cross Platform GUI Framework
Embarcadero Technologies
 
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
Embarcadero Technologies
 
FMXLinux Introduction - Delphi's FireMonkey for Linux
Embarcadero Technologies
 
RAD Industrial Automation, Labs, and Instrumentation
Embarcadero Technologies
 
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embarcadero Technologies
 
Rad Server Industry Template - Connected Nurses Station - Setup Document
Embarcadero Technologies
 
TMS Google Mapping Components
Embarcadero Technologies
 
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinar
Embarcadero Technologies
 
Useful C++ Features You Should be Using
Embarcadero Technologies
 
Getting Started Building Mobile Applications for iOS and Android
Embarcadero Technologies
 
Embarcadero RAD server Launch Webinar
Embarcadero Technologies
 
ER/Studio 2016: Build a Business-Driven Data Architecture
Embarcadero Technologies
 
The Secrets of SQL Server: Database Worst Practices
Embarcadero Technologies
 
Driving Business Value Through Agile Data Assets
Embarcadero Technologies
 
Troubleshooting Plan Changes with Query Store in SQL Server 2016
Embarcadero Technologies
 
Great Scott! Dealing with New Datatypes
Embarcadero Technologies
 
Agile, Automated, Aware: How to Model for Success
Embarcadero Technologies
 
Ad

Recently uploaded (20)

PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 

Python for Delphi Developers - Part 2

  • 1. Python for Delphi Developers (Part II) Webinar by Kiriakos Vlahos (aka PyScripter) and Jim McKeeth (Embarcadero)
  • 2. Contents •VarPyth Using python libraries and objects in Delphi code •Core libraries •Visualization •Machine Learning Python based data analytics in Delphi applications •TPythonThread Running python scripts without blocking your GUI Creating Python extension modules using Delphi •WrapDelphi and WrapDelphiVCL units Python GUI development using the VCL
  • 3. VarPyth • High-level access to python objects from Delphi code • It also allows you to create common python objects (lists, tuples etc.) • Uses custom variants • No need to use the low-level python API or deal with python object reference counting • Small performance penalty • Example • ShowMessage(SysModule.version) • Explore Demo25 and the VarPyth unit tests
  • 4. VarPyth Demoprocedure TForm1.FormCreate(Sender: TObject); begin var np := Import('numpy'); var np_array: Variant := np.array(VarPythonCreate([1,2,3,4,5,6,7,8,9,10])); PythonModule.SetVar('np_array’, ExtractPythonObjectFrom(np_array)); end; Python code: from delphi_module import np_array print("type(np_array) = ", type(np_array)) print("len(np_array) = ", len(np_array)) print("np_array = ", np_array) res_array = np_array.copy() for i in range(len(np_array)): res_array[i] *= np_array[i] print("res_array = ", res_array) Output: type(np_array) = <class 'numpy.ndarray'> len(np_array) = 10 np_array = [ 1 2 3 4 5 6 7 8 9 10] res_array = [ 1 4 9 16 25 36 49 64 81 100] procedure TForm1.btnRunClick(Sender: TObject); begin GetPythonEngine.ExecString(UTF8Encode(sePythonCode.Text)); for var V in VarPyIterate(MainModule.res_array) do ListBox.Items.Add(V); end; To learn more, explore Demo25 and the VarPyth unit tests
  • 5. Core Python Libraries • Core libraries • numpy – arrays and matrix algebra • scipy – math, science and engineering • pandas – data structure and analysis, R-like dataframes • Data visualization • matplotlib – matlab-like plotting • seaborn – statistical data visualization • mpld3 – turn matplotlib plots into interactive web pages • bokeh - interactive visualization library for modern browsers • plotly – interactive browser-based graphing library • altair – based on the visualization grammar vega-light
  • 6. Data visualization Demos - pyVIZsvg • Create charts with python libraries, save them in svg format and plot them in Delphi • Uses matplotlib and seaborn python libraries • Uses TSVGIconImage from EtheaDev SVGIconImageList components
  • 7. Interactive Data Visualization Demo - PychartHtml • Create interactive charts in python save them to html and show them inside Delphi applications • Showcases the new TEdgeBrowser • Uses the matplotlib with mpld3, altair and bohek python libraries
  • 8. Machine Learning Python Libraries • tensorflow (Google) • keras – high level pythonic interface • PyTorch (Facebook) • CNTK - The Microsoft Cognitive Toolkit (Microsoft) • Spark MLlib and mxnet (Apache Foundation) • scikit-learn • pure-python, general library, wide coverage, good choice for newcomers to ML/AI
  • 9. Data Analytics Demo: COVID-19 • Demonstrates the combined use of numpy, pandas, matplotlib and scikit-learn • Use pandas to download Covid-19 confirmed cases data from Web and aggregate it • Use scikit-learn to • Split the data into training and test sets • Transform the data • Define model (Bayesian Ridge Regression) • Optimize model parameters • Generate predictions • Use matplotlib to compare actual vrs fitted test data.
  • 10. Running Python Scripts Without Blocking Your Main Thread • Python uses the infamous Global Interpreter Lock (GIL) • This means that only one thread can run python code at any given time • Python switches between python created threads automatically • Applications using python need to acquire the GIL before running python code and release it soon afterwards • Welcome to TPythonThread • TThread descendent • Automatically acquires and releases the GIL
  • 11. Python threads – demo33 • Shows you how to • use TPythonThread • use new sub-interpreters • synchronize with the main thread • interrupt running threads with a keyboard interrupt exception
  • 12. Technical Aside I • FPU Exception mask • Delphi’s default FPU exception mask is different from most other Windows apps • Incompatible with python libraries written in C or C++ • If you use numpy, scipy, tensorflow etc. you need to match the FPU mask they expect to operate with • PythonEngine.pas provides a function for doing that: MaskFPUExceptions • Call MaskFPUExceptions(True) before python is loaded • e.g. the initialization section of your main form • See the P4D Wiki page for details
  • 13. Technical Aside II • Working with different python distributions: • P4D makes a good effort to discover registered python distributions automatically • But sometimes you want to use python distributions which are not registered • One such case is when want to deploy your application bundled with python. Python.org offers such a minimal distribution for applications embedding python. • Additional considerations apply when using an Anaconda distribution • Read the Finding Python P4D Wiki page carefully
  • 14. P4D Python Extension Modules • Python extension modules are dynamic link libraries that can be used by python in a way similar to modules developed in python. • They have ‘pyd’ extension. • P4D makes it very easy to create extension modules that contain functions and types developed in Delphi. • These extension modules can be used by Python, independently of Delphi, and can be packaged with setuptools and distributed through PyPi.
  • 15. Python extension modules Demo function PyInit_DemoModule: PPyObject; //function exported by dll – initializes the module begin try gEngine := TPythonEngine.Create(nil); gEngine.AutoFinalize := False; gEngine.UseLastKnownVersion := False; // Adapt to the desired python version gEngine.RegVersion := '3.8'; gEngine.DllName := 'python38.dll'; gModule := TPythonModule.Create(nil); gModule.Engine := gEngine; gModule.ModuleName := 'DemoModule'; gModule.AddMethod('is_prime', delphi_is_prime, 'is_prime(n) -> bool' ); gEngine.LoadDll; except end; Result := gModule.Module; end; Python test module: test.py from DemoModule import is_prime from timeit import Timer def count_primes(max_n): res = 0 for i in range(2, max_n + 1): if is_prime(i): res += 1 return res Command line: > C:PythonPython38python test.py Number of primes between 0 and 1000000 = 78498 Elapsed time: 0.29756570000000004 secs
  • 16. Wrapping VCL as a Python Extension Module I • We can use the same approach to create an extension module wrapping VCL • Uses the WrapDelphi and WrapDelphiVCL units • The whole of VCL (almost) is wrapped in 40 lines of code • The generated Delphi.pyd file is only 5Mbs • It can be uses to create VCL-based GUIs in python without needing Delphi • A similar approach could be used to wrap FMX and create a multi-platform python GUI library • Unclear whether there are licensing restrictions in distributing such a file
  • 17. Wrapping VCL as a Python Extension Module II unit uMain; interface uses PythonEngine; function PyInit_Delphi: PPyObject; cdecl; implementation uses WrapDelphi, WrapDelphiVCL; // similar to the previous extension module TestApp.py from Delphi import * class MainForm(Form): def __init__(self, Owner): self.Caption = "A Delphi Form..." self.SetBounds(10, 10, 500, 400) self.lblHello = Label(self) self.lblHello.SetProps(Parent=self, Caption="Hello World") self.lblHello.SetBounds(10, 10, 300, 24) self.OnClose = self.MainFormClose def MainFormClose(self, Sender, Action): Action.Value = caFree def main(): Application.Initialize() Application.Title = "MyDelphiApp" f = MainForm(Application) f.Show() FreeConsole() Application.Run() main() Command line: > C:PythonPython38python .TestApp.py
  • 18. Summary • With Python for Delphi you can get the best of both worlds • P4D makes it very easy to integrate Python into Delphi applications in RAD way, thus providing access to a vast range of python libraries • Expose Delphi function, objects, records and types to Python using low or high-level interfaces (WrapDelphi) • Create/Access/Use Python objects/modules in your Delphi code using a high- level interface (VarPyth) • Run python code in threads • Create python extensions modules • Wrap Vcl as a Python extension module to create GUIs with python github.com/pyscripter/python4delphi/tree/master/Tutorials/Webinar%20II