SlideShare a Scribd company logo
8
Most read
11
Most read
23
Most read
PYTHON FOR DELPHI
DEVELOPERS
Webinar by Kiriakos Vlahos (aka PyScripter)
and Jim McKeeth (Embarcadero)
CONTENTS
Motivation and Synergies
Introduction to Python
Introduction to Python for Delphi
Simple Demo
TPythonModule
TPyDelphiWrapper
PYTHON:
WHY
SHOULD I
(DELPHI
DEVELOPER)
CARE?
Massive increase in popularity
Language of choice for Data Analytics and Machine
Learning/Artificial Intelligence
Rapidly replacing Java as the core programming language in
Computer Science degrees
Huge number of packages
available (250K at PyPI)
All the latest and greatest open-source
libraries are available to Python
immediately
Perceived as productive and easy to learn
Complementary strengths with Delphi
PYTHON-
DELPHI:
POTENTIAL
SYNERGIES
Gain access to Python libraries from your Delphi applications
Use Python as a scripting language for Delphi applications
Make code developed in Delphi accessible from python scripts
Bring together RAD and GUI Delphi development with python
programming
Combine the strengths of each language
POPULARITY OF PYTHON
PYTHON VS. JAVA
Interest over time (Google Trends)
Java
Python
DELPHI VS PYTHON
Delphi/Pascal Python
Maturity (1995/1970!) (1989)
Object orientation
Multi-platform
Verbosity High (begin end) Low (indentation based)
REPL No Yes
Typing Strong static typing Dynamic (duck) typing
Memory management Manual Reference counting
Compiled bytecode
Performance
Multi-threading
RAD
PYTHON FOR DELPHI (I)
Low-level access to the
python API
High-level bi-directional
interaction with Python
Access to Python objects
using Delphi custom
variants
Wrapping of Delphi
objects for use in python
scripts using RTTI
Creating python extension
modules with Delphi
classes and functions
PYTHON FOR DELPHI (II)
• Delphi version support
• 2009 or later
• Platform support
• Windows 32 & 64 bits
• Linux
• MacOS
• Mostly non-visual components
• Can be used in console applications
• Lazarus/FPC support
GETTING STARTED – INSTALLING
PYTHON
• Select a Python distribution
• www.python.org (official distribution)
• Anaconda (recommended for heavy data-analytics work)
• Python 2 vs. Python 3
• 32-bits vs. 64-bits
• Download and run the installer
• Installation options (location, for all users)
• Install python packages you are planning to use (can be done later)
• Use the python package installer (pip) from the command prompt
• eg. > pip install numpy
GETTING STARTED – INSTALLING
PYTHON FOR DELPHI
• Clone or download and unzip the Github repository into a directory (e.g.,
D:ComponentsP4D).
• Start RAD Studio.
• Add the source subdirectory (e.g., D:ComponentsP4DSource) to the IDE's library
path for the targets you are planning to use.
• Open and install the Python4Delphi package specific to the IDE being used. For
Delphi Sydney and later it can be found in the PackagesDelphiDelphi 10.4+
directory. For earlier versions use the package in the PackagesDelphiDelphi 10.3-
directory.
Note: The package is Design & Runtime together
P4D COMPONENTS
Component Functionality
PythonEngine Load and connect to Python. Access to Python API (low-level)
PythonModule Create a Python module in Delphi and make it accessible to Python
PythonType Create a python type (class) in Delphi
PythonInputOutput Receive python output
PythonGUIInputOutput Send python output to a Memo
PyDelphiWrapper Make Delphi classes and objects accessible from Python (hi-level)
VarPython Hi-level access to Python objects from Delphi using custom variants
(unit not a component)
SIMPLE DEMO
(I)
SynEdit
Memo
SIMPLE DEMO
(II)
• All components are using default properties
• PythonGUIInputOutput linked to PythonEngine and
Memo
• Source Code:
procedure TForm1.btnRunClick(Sender: TObject);
begin
GetPythonEngine.ExecString(UTF8Encode(sePythonC
ode.Text));
end;
USING TPYTHONMODULE (I)
Python
def is_prime(n):
""" totally naive implementation """
if n <= 1:
return False
q = math.floor(math.sqrt(n))
for i in range(2, q + 1):
if (n % i == 0):
return False
return True
Delphi
function IsPrime(x: Integer): Boolean;
begin
if (x <= 1) then Exit(False);
var q := Floor(Sqrt(x));
for var i := 2 to q do
if (x mod i = 0) then
Exit(False);
Exit(True);
end;
Python
def count_primes(max_n):
res = 0
for i in range(2, max_n + 1):
if is_prime(i):
res += 1
return res
def test():
max_n = 1000000
print(f'Number of primes between 0 and {max_n} = {count_primes(max_n)}')
def main():
print(f'Elapsed time: {Timer(stmt=test).timeit(1)} secs')
if __name__ == '__main__':
main()
USING TPYTHONMODULE (II)
Output
Number of primes between 0 and 1000000 = 78498
Elapsed time: 3.4528134000000037 secs
USING TPYTHONMODULE (III)
• Add a TPythonModule to the form and link it to the PythonEngine
• ModuleName: delphi_module
• Implement python function delphi_is_prime by writing a Delphi event
procedure TForm1.PythonModuleEvents0Execute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject);
Var
N: Integer;
begin
with GetPythonEngine do
if PyArg_ParseTuple(Args, 'i:delphi_is_prime',@N) <> 0 then
begin
if IsPrime(N) then
Result := PPyObject(Py_True)
else
Result := PPyObject(Py_False);
Py_INCREF(Result);
end else
Result := nil;
end;
Python
from delphi_module import delphi_is_prime
def count_primes(max_n):
res = 0
for i in range(2, max_n + 1):
if delphi_is_prime(i):
res += 1
return res
USING TPYTHONMODULE (IV)
Output
Number of primes between 0 and 1000000 = 78498
Elapsed time: 0.3073742000000017 secs
10x + improvement!
But hold on. Delphi can do something python can’t
do easily: Use threads and multiple CPU cores
USING TPYTHONMODULE (V)
• Implement delphi_count_primes using TParallel.For
function CountPrimes(MaxN: integer): integer;
begin
var Count := 0;
TParallel.&For(2, MaxN, procedure(i: integer)
begin
if IsPrime(i) then
AtomicIncrement(Count);
end);
Result := Count;
end;
Output
Number of primes between 0 and 1000000 = 78498
Elapsed time: 0.04709590000000219 secs
70x + improvement!
Python
from delphi_module import delphi_count_primes
from timeit import Timer
import math
def test():
max_n = 1000000
print(f'Number of primes between 0 and {max_n} = {delphi_count_primes(max_n)}')
USING PYDELPHIWRAPPER
• PyDelphiWrapper allows you to expose Delphi objects, records and types using RTTI
and cusomised wrapping of common Delphi objects.
• Add a TPyDelphiWrapper on the form and link it to a PythonModule.
• In this demo we will wrap a Delphi record containing a class function.
type
TDelphiFunctions = record
class function count_primes(MaxN: integer): integer; static;
end;
var
DelphiFunctions: TDelphiFunctions;
procedure TForm1.FormCreate(Sender: TObject);
begin
var Py := PyDelphiWrapper.WrapRecord(@DelphiFunctions,
TRttiContext.Create.GetType(TypeInfo(TDelphiFunctions))
as TRttiStructuredType);
PythonModule.SetVar('delphi_functions', Py);
PythonEngine.Py_DecRef(Py);
end;
WRAPDELPHI DEMO31
• Shows you how you can create Delphi GUIs with Python
• Create forms
• Subclass Forms (and other Delphi types)
• Add python Form event handlers
• Use customized wrapping of common RTL and VCL objects
• Common Dialogs
• StringLists
• Exception handling
CONCLUSIONS
• 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
• Expose Delphi function, objects, records and types to Python using low or high-level
interfaces
• In a future webinar we will cover
• Using python libraries and objects in Delphi code (VarPyth)
• Python based data analytics in Delphi applications
• Creating Python extension modules using Delphi
• Python GUI development using the VCL
RESOURCES
• Python4Delphi library
• https://github.com/pyscripter/python4delphi
• PyScripter IDE
• https://github.com/pyscripter/pyscripter
• Thinking in CS – Python3 Tutorial
• https://openbookproject.net/thinkcs/python/english3e/
• PyScripter blog
• https://pyscripter.blogspot.com/
• Webinar blog post
• https://blogs.embarcadero.com/python-for-delphi-developers-webinar/

More Related Content

PDF
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
Embarcadero Technologies
 
PDF
Introduction to eBPF and XDP
lcplcp1
 
PDF
Python on Android with Delphi FMX - The Cross Platform GUI Framework
Embarcadero Technologies
 
PDF
Introduce to Terraform
Samsung Electronics
 
PDF
Container Network Interface: Network Plugins for Kubernetes and beyond
KubeAcademy
 
PPTX
Verilator勉強会 2021/05/29
ryuz88
 
PDF
FPGAアクセラレータの作り方
Mr. Vengineer
 
PDF
eBPF/XDP
Netronome
 
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
Embarcadero Technologies
 
Introduction to eBPF and XDP
lcplcp1
 
Python on Android with Delphi FMX - The Cross Platform GUI Framework
Embarcadero Technologies
 
Introduce to Terraform
Samsung Electronics
 
Container Network Interface: Network Plugins for Kubernetes and beyond
KubeAcademy
 
Verilator勉強会 2021/05/29
ryuz88
 
FPGAアクセラレータの作り方
Mr. Vengineer
 
eBPF/XDP
Netronome
 

What's hot (20)

PPSX
Slides: New Practical Chinese Reader Textbook1 Lesson 1 《新实用汉语课本》第1册第1课课件
Phoenix Tree Publishing Inc
 
PDF
Boostのあるプログラミング生活
Akira Takahashi
 
PDF
Linux KVM環境におけるGPGPU活用最新動向
Taira Hajime
 
PDF
Room 2 - 3 - Nguyễn Hoài Nam & Nguyễn Việt Hùng - Terraform & Pulumi Comparin...
Vietnam Open Infrastructure User Group
 
PDF
Vector Codegen in the RISC-V Backend
Igalia
 
PDF
Dockerfile
Jeffrey Ellin
 
PDF
Microsoft Project Online with PowerBI
Hari Thapliyal
 
PPTX
Container Networking Deep Dive
Hirofumi Ichihara
 
PDF
KFServing and Kubeflow Pipelines
Animesh Singh
 
PDF
Zynq mp勉強会資料
一路 川染
 
PDF
Dockerを支える技術
Etsuji Nakai
 
PDF
Osic tech talk presentation on ironic inspector
Annie Lezil
 
PPTX
차세대 데이터센터 네트워크 전략
Woo Hyung Choi
 
PDF
Open vSwitchソースコードの全体像
Sho Shimizu
 
PDF
Introduction to Docker Compose
Ajeet Singh Raina
 
PDF
Continuous Integration/Deployment with Gitlab CI
David Hahn
 
PDF
Vivado hls勉強会1(基礎編)
marsee101
 
PDF
Red Hat OpenStack 17 저자직강+스터디그룹_5주차
Nalee Jang
 
PDF
Kubernetes Networking with Cilium - Deep Dive
Michal Rostecki
 
PDF
Fun with PRB, VRFs and NetNS on Linux - What is it, how does it work, what ca...
Maximilan Wilhelm
 
Slides: New Practical Chinese Reader Textbook1 Lesson 1 《新实用汉语课本》第1册第1课课件
Phoenix Tree Publishing Inc
 
Boostのあるプログラミング生活
Akira Takahashi
 
Linux KVM環境におけるGPGPU活用最新動向
Taira Hajime
 
Room 2 - 3 - Nguyễn Hoài Nam & Nguyễn Việt Hùng - Terraform & Pulumi Comparin...
Vietnam Open Infrastructure User Group
 
Vector Codegen in the RISC-V Backend
Igalia
 
Dockerfile
Jeffrey Ellin
 
Microsoft Project Online with PowerBI
Hari Thapliyal
 
Container Networking Deep Dive
Hirofumi Ichihara
 
KFServing and Kubeflow Pipelines
Animesh Singh
 
Zynq mp勉強会資料
一路 川染
 
Dockerを支える技術
Etsuji Nakai
 
Osic tech talk presentation on ironic inspector
Annie Lezil
 
차세대 데이터센터 네트워크 전략
Woo Hyung Choi
 
Open vSwitchソースコードの全体像
Sho Shimizu
 
Introduction to Docker Compose
Ajeet Singh Raina
 
Continuous Integration/Deployment with Gitlab CI
David Hahn
 
Vivado hls勉強会1(基礎編)
marsee101
 
Red Hat OpenStack 17 저자직강+스터디그룹_5주차
Nalee Jang
 
Kubernetes Networking with Cilium - Deep Dive
Michal Rostecki
 
Fun with PRB, VRFs and NetNS on Linux - What is it, how does it work, what ca...
Maximilan Wilhelm
 
Ad

Similar to Python for Delphi Developers - Part 1 Introduction (20)

PDF
EKON 25 Python4Delphi_mX4
Max Kleiner
 
PDF
Ekon 25 Python4Delphi_MX475
Max Kleiner
 
PDF
Python for Delphi Developers - Part 2
Embarcadero Technologies
 
PDF
PyTorch for Delphi - Python Data Sciences Libraries.pdf
Embarcadero Technologies
 
PDF
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
pythoncharmers
 
PPTX
Delphi
Avinash kumar
 
PPT
Introduction to python & its applications.ppt
PradeepNB2
 
PDF
Programming RPi for IoT Applications.pdf
rakeshk213994
 
PPT
C463_02_python.ppt
DiegoARosales
 
PPT
C463_02_python.ppt
athulprathap1
 
PDF
SnW: Introduction to PYNQ Platform and Python Language
NECST Lab @ Politecnico di Milano
 
PPT
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
divijareddy0502
 
PPT
C463_02intoduction_to_python_to learnGAI.ppt
AhmedHamzaJandoubi
 
PDF
PyCon2022 - Building Python Extensions
Henry Schreiner
 
PPTX
Basic data types in python
sunilchute1
 
PDF
Py tut-handout
Ramachandra Dama
 
PDF
PyCon Estonia 2019
Travis Oliphant
 
PDF
SunPy: Python for solar physics
segfaulthunter
 
PPTX
Python introduction towards data science
deepak teja
 
EKON 25 Python4Delphi_mX4
Max Kleiner
 
Ekon 25 Python4Delphi_MX475
Max Kleiner
 
Python for Delphi Developers - Part 2
Embarcadero Technologies
 
PyTorch for Delphi - Python Data Sciences Libraries.pdf
Embarcadero Technologies
 
Python for Science and Engineering: a presentation to A*STAR and the Singapor...
pythoncharmers
 
Introduction to python & its applications.ppt
PradeepNB2
 
Programming RPi for IoT Applications.pdf
rakeshk213994
 
C463_02_python.ppt
DiegoARosales
 
C463_02_python.ppt
athulprathap1
 
SnW: Introduction to PYNQ Platform and Python Language
NECST Lab @ Politecnico di Milano
 
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
divijareddy0502
 
C463_02intoduction_to_python_to learnGAI.ppt
AhmedHamzaJandoubi
 
PyCon2022 - Building Python Extensions
Henry Schreiner
 
Basic data types in python
sunilchute1
 
Py tut-handout
Ramachandra Dama
 
PyCon Estonia 2019
Travis Oliphant
 
SunPy: Python for solar physics
segfaulthunter
 
Python introduction towards data science
deepak teja
 
Ad

More from Embarcadero Technologies (20)

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
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
 
PDF
What's New in DBArtisan and Rapid SQL 2016
Embarcadero Technologies
 
PDF
Is This Really a SAN Problem? Understanding the Performance of Your IO Subsy...
Embarcadero Technologies
 
PDF
RAD Studio, Delphi and C++Builder 10 Feature Matrix
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
 
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
 
What's New in DBArtisan and Rapid SQL 2016
Embarcadero Technologies
 
Is This Really a SAN Problem? Understanding the Performance of Your IO Subsy...
Embarcadero Technologies
 
RAD Studio, Delphi and C++Builder 10 Feature Matrix
Embarcadero Technologies
 

Recently uploaded (20)

PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PPTX
Smart Panchayat Raj e-Governance App.pptx
Rohitnikam33
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PPTX
oapresentation.pptx
mehatdhavalrajubhai
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Smart Panchayat Raj e-Governance App.pptx
Rohitnikam33
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
QAware GmbH
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
oapresentation.pptx
mehatdhavalrajubhai
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Presentation about variables and constant.pptx
safalsingh810
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 

Python for Delphi Developers - Part 1 Introduction

  • 1. PYTHON FOR DELPHI DEVELOPERS Webinar by Kiriakos Vlahos (aka PyScripter) and Jim McKeeth (Embarcadero)
  • 2. CONTENTS Motivation and Synergies Introduction to Python Introduction to Python for Delphi Simple Demo TPythonModule TPyDelphiWrapper
  • 3. PYTHON: WHY SHOULD I (DELPHI DEVELOPER) CARE? Massive increase in popularity Language of choice for Data Analytics and Machine Learning/Artificial Intelligence Rapidly replacing Java as the core programming language in Computer Science degrees Huge number of packages available (250K at PyPI) All the latest and greatest open-source libraries are available to Python immediately Perceived as productive and easy to learn Complementary strengths with Delphi
  • 4. PYTHON- DELPHI: POTENTIAL SYNERGIES Gain access to Python libraries from your Delphi applications Use Python as a scripting language for Delphi applications Make code developed in Delphi accessible from python scripts Bring together RAD and GUI Delphi development with python programming Combine the strengths of each language
  • 6. PYTHON VS. JAVA Interest over time (Google Trends) Java Python
  • 7. DELPHI VS PYTHON Delphi/Pascal Python Maturity (1995/1970!) (1989) Object orientation Multi-platform Verbosity High (begin end) Low (indentation based) REPL No Yes Typing Strong static typing Dynamic (duck) typing Memory management Manual Reference counting Compiled bytecode Performance Multi-threading RAD
  • 8. PYTHON FOR DELPHI (I) Low-level access to the python API High-level bi-directional interaction with Python Access to Python objects using Delphi custom variants Wrapping of Delphi objects for use in python scripts using RTTI Creating python extension modules with Delphi classes and functions
  • 9. PYTHON FOR DELPHI (II) • Delphi version support • 2009 or later • Platform support • Windows 32 & 64 bits • Linux • MacOS • Mostly non-visual components • Can be used in console applications • Lazarus/FPC support
  • 10. GETTING STARTED – INSTALLING PYTHON • Select a Python distribution • www.python.org (official distribution) • Anaconda (recommended for heavy data-analytics work) • Python 2 vs. Python 3 • 32-bits vs. 64-bits • Download and run the installer • Installation options (location, for all users) • Install python packages you are planning to use (can be done later) • Use the python package installer (pip) from the command prompt • eg. > pip install numpy
  • 11. GETTING STARTED – INSTALLING PYTHON FOR DELPHI • Clone or download and unzip the Github repository into a directory (e.g., D:ComponentsP4D). • Start RAD Studio. • Add the source subdirectory (e.g., D:ComponentsP4DSource) to the IDE's library path for the targets you are planning to use. • Open and install the Python4Delphi package specific to the IDE being used. For Delphi Sydney and later it can be found in the PackagesDelphiDelphi 10.4+ directory. For earlier versions use the package in the PackagesDelphiDelphi 10.3- directory. Note: The package is Design & Runtime together
  • 12. P4D COMPONENTS Component Functionality PythonEngine Load and connect to Python. Access to Python API (low-level) PythonModule Create a Python module in Delphi and make it accessible to Python PythonType Create a python type (class) in Delphi PythonInputOutput Receive python output PythonGUIInputOutput Send python output to a Memo PyDelphiWrapper Make Delphi classes and objects accessible from Python (hi-level) VarPython Hi-level access to Python objects from Delphi using custom variants (unit not a component)
  • 14. SIMPLE DEMO (II) • All components are using default properties • PythonGUIInputOutput linked to PythonEngine and Memo • Source Code: procedure TForm1.btnRunClick(Sender: TObject); begin GetPythonEngine.ExecString(UTF8Encode(sePythonC ode.Text)); end;
  • 15. USING TPYTHONMODULE (I) Python def is_prime(n): """ totally naive implementation """ if n <= 1: return False q = math.floor(math.sqrt(n)) for i in range(2, q + 1): if (n % i == 0): return False return True Delphi function IsPrime(x: Integer): Boolean; begin if (x <= 1) then Exit(False); var q := Floor(Sqrt(x)); for var i := 2 to q do if (x mod i = 0) then Exit(False); Exit(True); end;
  • 16. Python def count_primes(max_n): res = 0 for i in range(2, max_n + 1): if is_prime(i): res += 1 return res def test(): max_n = 1000000 print(f'Number of primes between 0 and {max_n} = {count_primes(max_n)}') def main(): print(f'Elapsed time: {Timer(stmt=test).timeit(1)} secs') if __name__ == '__main__': main() USING TPYTHONMODULE (II) Output Number of primes between 0 and 1000000 = 78498 Elapsed time: 3.4528134000000037 secs
  • 17. USING TPYTHONMODULE (III) • Add a TPythonModule to the form and link it to the PythonEngine • ModuleName: delphi_module • Implement python function delphi_is_prime by writing a Delphi event procedure TForm1.PythonModuleEvents0Execute(Sender: TObject; PSelf, Args: PPyObject; var Result: PPyObject); Var N: Integer; begin with GetPythonEngine do if PyArg_ParseTuple(Args, 'i:delphi_is_prime',@N) <> 0 then begin if IsPrime(N) then Result := PPyObject(Py_True) else Result := PPyObject(Py_False); Py_INCREF(Result); end else Result := nil; end;
  • 18. Python from delphi_module import delphi_is_prime def count_primes(max_n): res = 0 for i in range(2, max_n + 1): if delphi_is_prime(i): res += 1 return res USING TPYTHONMODULE (IV) Output Number of primes between 0 and 1000000 = 78498 Elapsed time: 0.3073742000000017 secs 10x + improvement! But hold on. Delphi can do something python can’t do easily: Use threads and multiple CPU cores
  • 19. USING TPYTHONMODULE (V) • Implement delphi_count_primes using TParallel.For function CountPrimes(MaxN: integer): integer; begin var Count := 0; TParallel.&For(2, MaxN, procedure(i: integer) begin if IsPrime(i) then AtomicIncrement(Count); end); Result := Count; end; Output Number of primes between 0 and 1000000 = 78498 Elapsed time: 0.04709590000000219 secs 70x + improvement! Python from delphi_module import delphi_count_primes from timeit import Timer import math def test(): max_n = 1000000 print(f'Number of primes between 0 and {max_n} = {delphi_count_primes(max_n)}')
  • 20. USING PYDELPHIWRAPPER • PyDelphiWrapper allows you to expose Delphi objects, records and types using RTTI and cusomised wrapping of common Delphi objects. • Add a TPyDelphiWrapper on the form and link it to a PythonModule. • In this demo we will wrap a Delphi record containing a class function. type TDelphiFunctions = record class function count_primes(MaxN: integer): integer; static; end; var DelphiFunctions: TDelphiFunctions; procedure TForm1.FormCreate(Sender: TObject); begin var Py := PyDelphiWrapper.WrapRecord(@DelphiFunctions, TRttiContext.Create.GetType(TypeInfo(TDelphiFunctions)) as TRttiStructuredType); PythonModule.SetVar('delphi_functions', Py); PythonEngine.Py_DecRef(Py); end;
  • 21. WRAPDELPHI DEMO31 • Shows you how you can create Delphi GUIs with Python • Create forms • Subclass Forms (and other Delphi types) • Add python Form event handlers • Use customized wrapping of common RTL and VCL objects • Common Dialogs • StringLists • Exception handling
  • 22. CONCLUSIONS • 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 • Expose Delphi function, objects, records and types to Python using low or high-level interfaces • In a future webinar we will cover • Using python libraries and objects in Delphi code (VarPyth) • Python based data analytics in Delphi applications • Creating Python extension modules using Delphi • Python GUI development using the VCL
  • 23. RESOURCES • Python4Delphi library • https://github.com/pyscripter/python4delphi • PyScripter IDE • https://github.com/pyscripter/pyscripter • Thinking in CS – Python3 Tutorial • https://openbookproject.net/thinkcs/python/english3e/ • PyScripter blog • https://pyscripter.blogspot.com/ • Webinar blog post • https://blogs.embarcadero.com/python-for-delphi-developers-webinar/