SlideShare a Scribd company logo
1 of 23
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

What's hot

Timeseries - data visualization in Grafana
Timeseries - data visualization in GrafanaTimeseries - data visualization in Grafana
Timeseries - data visualization in GrafanaOCoderFest
 
JVM code reading -- C2
JVM code reading -- C2JVM code reading -- C2
JVM code reading -- C2ytoshima
 
Mixing Scala and Kotlin
Mixing Scala and KotlinMixing Scala and Kotlin
Mixing Scala and KotlinAlexey Soshin
 
LLVM Backend Porting
LLVM Backend PortingLLVM Backend Porting
LLVM Backend PortingShiva Chen
 
Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013
Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013
Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013dotCloud
 
PythonとVeriloggenを用いたRTL設計メタプログラミング
PythonとVeriloggenを用いたRTL設計メタプログラミングPythonとVeriloggenを用いたRTL設計メタプログラミング
PythonとVeriloggenを用いたRTL設計メタプログラミングShinya Takamaeda-Y
 
Triton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON ChinaTriton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON ChinaWei-Bo Chen
 
CICD using jenkins and Nomad
CICD using jenkins and NomadCICD using jenkins and Nomad
CICD using jenkins and NomadBram Vogelaar
 
Kernel Module Programming
Kernel Module ProgrammingKernel Module Programming
Kernel Module ProgrammingSaurabh Bangad
 
CMake multiplatform build-tool
CMake multiplatform build-toolCMake multiplatform build-tool
CMake multiplatform build-toolNaruto TAKAHASHI
 
(JP) GPGPUがPostgreSQLを加速する
(JP) GPGPUがPostgreSQLを加速する(JP) GPGPUがPostgreSQLを加速する
(JP) GPGPUがPostgreSQLを加速するKohei KaiGai
 
Stack Buffer OverFlow
Stack Buffer OverFlowStack Buffer OverFlow
Stack Buffer OverFlowsounakano
 
PromQL Deep Dive - The Prometheus Query Language
PromQL Deep Dive - The Prometheus Query Language PromQL Deep Dive - The Prometheus Query Language
PromQL Deep Dive - The Prometheus Query Language Weaveworks
 

What's hot (20)

Timeseries - data visualization in Grafana
Timeseries - data visualization in GrafanaTimeseries - data visualization in Grafana
Timeseries - data visualization in Grafana
 
JVM code reading -- C2
JVM code reading -- C2JVM code reading -- C2
JVM code reading -- C2
 
Mixing Scala and Kotlin
Mixing Scala and KotlinMixing Scala and Kotlin
Mixing Scala and Kotlin
 
LLVM Backend Porting
LLVM Backend PortingLLVM Backend Porting
LLVM Backend Porting
 
TaPL9
TaPL9TaPL9
TaPL9
 
Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013
Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013
Write Once and REALLY Run Anywhere | OpenStack Summit HK 2013
 
Github in Action
Github in ActionGithub in Action
Github in Action
 
PythonとVeriloggenを用いたRTL設計メタプログラミング
PythonとVeriloggenを用いたRTL設計メタプログラミングPythonとVeriloggenを用いたRTL設計メタプログラミング
PythonとVeriloggenを用いたRTL設計メタプログラミング
 
Triton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON ChinaTriton and Symbolic execution on GDB@DEF CON China
Triton and Symbolic execution on GDB@DEF CON China
 
CICD using jenkins and Nomad
CICD using jenkins and NomadCICD using jenkins and Nomad
CICD using jenkins and Nomad
 
Git and Github Session
Git and Github SessionGit and Github Session
Git and Github Session
 
presentation on Docker
presentation on Dockerpresentation on Docker
presentation on Docker
 
Kernel Module Programming
Kernel Module ProgrammingKernel Module Programming
Kernel Module Programming
 
Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
 
CMake multiplatform build-tool
CMake multiplatform build-toolCMake multiplatform build-tool
CMake multiplatform build-tool
 
golang profiling の基礎
golang profiling の基礎golang profiling の基礎
golang profiling の基礎
 
(JP) GPGPUがPostgreSQLを加速する
(JP) GPGPUがPostgreSQLを加速する(JP) GPGPUがPostgreSQLを加速する
(JP) GPGPUがPostgreSQLを加速する
 
Room 2 - 1 - Phạm Quang Minh - A real DevOps culture in practice
Room 2 - 1 - Phạm Quang Minh - A real DevOps culture in practiceRoom 2 - 1 - Phạm Quang Minh - A real DevOps culture in practice
Room 2 - 1 - Phạm Quang Minh - A real DevOps culture in practice
 
Stack Buffer OverFlow
Stack Buffer OverFlowStack Buffer OverFlow
Stack Buffer OverFlow
 
PromQL Deep Dive - The Prometheus Query Language
PromQL Deep Dive - The Prometheus Query Language PromQL Deep Dive - The Prometheus Query Language
PromQL Deep Dive - The Prometheus Query Language
 

Similar to Python for Delphi Developers - Part 1 Introduction

EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4Max Kleiner
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
Introduction to python & its applications.ppt
Introduction to python & its applications.pptIntroduction to python & its applications.ppt
Introduction to python & its applications.pptPradeepNB2
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.pptKapilMighani
 
kapil presentation.ppt
kapil presentation.pptkapil presentation.ppt
kapil presentation.pptKapilMighani
 
Python: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaPython: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaActiveState
 
running Tensorflow in Production
running Tensorflow in Productionrunning Tensorflow in Production
running Tensorflow in ProductionMatthias Feys
 
Python Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IPython Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IDUSPviz
 
Flink Forward SF 2017: Eron Wright - Introducing Flink Tensorflow
Flink Forward SF 2017: Eron Wright - Introducing Flink TensorflowFlink Forward SF 2017: Eron Wright - Introducing Flink Tensorflow
Flink Forward SF 2017: Eron Wright - Introducing Flink TensorflowFlink Forward
 
Collective Communications in MPI
 Collective Communications in MPI Collective Communications in MPI
Collective Communications in MPIHanif Durad
 
Sour Pickles
Sour PicklesSour Pickles
Sour PicklesSensePost
 

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

EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Introduction to python & its applications.ppt
Introduction to python & its applications.pptIntroduction to python & its applications.ppt
Introduction to python & its applications.ppt
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
 
kapil presentation.ppt
kapil presentation.pptkapil presentation.ppt
kapil presentation.ppt
 
Python: The Programmer's Lingua Franca
Python: The Programmer's Lingua FrancaPython: The Programmer's Lingua Franca
Python: The Programmer's Lingua Franca
 
running Tensorflow in Production
running Tensorflow in Productionrunning Tensorflow in Production
running Tensorflow in Production
 
Python Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IPython Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part I
 
Flink Forward SF 2017: Eron Wright - Introducing Flink Tensorflow
Flink Forward SF 2017: Eron Wright - Introducing Flink TensorflowFlink Forward SF 2017: Eron Wright - Introducing Flink Tensorflow
Flink Forward SF 2017: Eron Wright - Introducing Flink Tensorflow
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Collective Communications in MPI
 Collective Communications in MPI Collective Communications in MPI
Collective Communications in MPI
 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
 
The Python Programming Language and HDF5: H5Py
The Python Programming Language and HDF5: H5PyThe Python Programming Language and HDF5: H5Py
The Python Programming Language and HDF5: H5Py
 
Mpi in-python
Mpi in-pythonMpi in-python
Mpi in-python
 

More from Embarcadero Technologies

PyTorch for Delphi - Python Data Sciences Libraries.pdf
PyTorch for Delphi - Python Data Sciences Libraries.pdfPyTorch for Delphi - Python Data Sciences Libraries.pdf
PyTorch for Delphi - Python Data Sciences Libraries.pdfEmbarcadero Technologies
 
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...
Android on Windows 11 - A Developer's Perspective (Windows Subsystem For Andr...Embarcadero Technologies
 
Linux GUI Applications on Windows Subsystem for Linux
Linux GUI Applications on Windows Subsystem for LinuxLinux GUI Applications on Windows Subsystem for Linux
Linux GUI Applications on Windows Subsystem for LinuxEmbarcadero Technologies
 
Introduction to Python GUI development with Delphi for Python - Part 1: Del...
Introduction to Python GUI development with Delphi for Python - Part 1:   Del...Introduction to Python GUI development with Delphi for Python - Part 1:   Del...
Introduction to Python GUI development with Delphi for Python - Part 1: Del...Embarcadero Technologies
 
FMXLinux Introduction - Delphi's FireMonkey for Linux
FMXLinux Introduction - Delphi's FireMonkey for LinuxFMXLinux Introduction - Delphi's FireMonkey for Linux
FMXLinux Introduction - Delphi's FireMonkey for LinuxEmbarcadero Technologies
 
RAD Industrial Automation, Labs, and Instrumentation
RAD Industrial Automation, Labs, and InstrumentationRAD Industrial Automation, Labs, and Instrumentation
RAD Industrial Automation, Labs, and InstrumentationEmbarcadero Technologies
 
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBaseEmbeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBaseEmbarcadero Technologies
 
Rad Server Industry Template - Connected Nurses Station - Setup Document
Rad Server Industry Template - Connected Nurses Station - Setup DocumentRad Server Industry Template - Connected Nurses Station - Setup Document
Rad Server Industry Template - Connected Nurses Station - Setup DocumentEmbarcadero Technologies
 
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinar
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinarMove Desktop Apps to the Cloud - RollApp & Embarcadero webinar
Move Desktop Apps to the Cloud - RollApp & Embarcadero webinarEmbarcadero Technologies
 
Getting Started Building Mobile Applications for iOS and Android
Getting Started Building Mobile Applications for iOS and AndroidGetting Started Building Mobile Applications for iOS and Android
Getting Started Building Mobile Applications for iOS and AndroidEmbarcadero Technologies
 
ER/Studio 2016: Build a Business-Driven Data Architecture
ER/Studio 2016: Build a Business-Driven Data ArchitectureER/Studio 2016: Build a Business-Driven Data Architecture
ER/Studio 2016: Build a Business-Driven Data ArchitectureEmbarcadero Technologies
 
The Secrets of SQL Server: Database Worst Practices
The Secrets of SQL Server: Database Worst PracticesThe Secrets of SQL Server: Database Worst Practices
The Secrets of SQL Server: Database Worst PracticesEmbarcadero Technologies
 
Driving Business Value Through Agile Data Assets
Driving Business Value Through Agile Data AssetsDriving Business Value Through Agile Data Assets
Driving Business Value Through Agile Data AssetsEmbarcadero Technologies
 
Troubleshooting Plan Changes with Query Store in SQL Server 2016
Troubleshooting Plan Changes with Query Store in SQL Server 2016Troubleshooting Plan Changes with Query Store in SQL Server 2016
Troubleshooting Plan Changes with Query Store in SQL Server 2016Embarcadero Technologies
 
Agile, Automated, Aware: How to Model for Success
Agile, Automated, Aware: How to Model for SuccessAgile, Automated, Aware: How to Model for Success
Agile, Automated, Aware: How to Model for SuccessEmbarcadero Technologies
 
What's New in DBArtisan and Rapid SQL 2016
What's New in DBArtisan and Rapid SQL 2016What's New in DBArtisan and Rapid SQL 2016
What's New in DBArtisan and Rapid SQL 2016Embarcadero Technologies
 

More from Embarcadero Technologies (20)

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

Recently uploaded

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 

Recently uploaded (20)

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 

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/