100% found this document useful (1 vote)
629 views

EKON 25 Python4Delphi MX4

Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). They let you easily execute Python scripts, create new Python modules and new Python types. You can create Python extensions as DLLs and much more like scripting. P4D provides different levels of functionality: Low-level access to the python API High-level bi-directional interaction with Python Access to Python objects using Delphi custom variants (VarPyth.pas) Wrapping

Uploaded by

Max Kleiner
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
629 views

EKON 25 Python4Delphi MX4

Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). They let you easily execute Python scripts, create new Python modules and new Python types. You can create Python extensions as DLLs and much more like scripting. P4D provides different levels of functionality: Low-level access to the python API High-level bi-directional interaction with Python Access to Python objects using Delphi custom variants (VarPyth.pas) Wrapping

Uploaded by

Max Kleiner
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Python for Delphi Developers

Max Kleiner
Python-Delphi: Potential Synergies

Jupyter Notebook
Jupyter is a spin-off project from IPython, aiming to standardize interactive computing in any
programming languages. The kernel provides interactive environment that executes user code as a
server, connected with a frontend through sockets. A Jupyter Notebook is also an open-source web
application that allows you to create and share documents that contain live code, equations,
visualizations, and describing text.

Google Colab
With Colab you can import an image dataset, train an image classifier on it, and evaluate the model, all in
just a few lines of code. Colab notebooks execute code on Google’s cloud servers, meaning you can
leverage the power of Google hardware, including GPUs and TPUs, regardless of the power of your
machine.

TPU
Tensor Processing Unit (TPU) is an AI accelerator application-specific integrated circuit (ASIC) developed
by Google specifically for neural network machine learning, particularly using Google’s own TensorFlow
software.
Popularity of Python

https://www.tiobe.com/tiobe-index/
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)
Imagine you need a 512bit hash (or another master of reality procedure) and you don’t have the available function.

eng:= TPythonEngine.Create(Nil);
eng.pythonhome:= PYHOME;
eng.opendll(PYDLL)
//eng.IO:= pyMemo;
try
eng.Execstring('with open(r"'+exepath+'maXbox4.exe","rb") as afile:'+
' fbuf = afile.read()');
println(eng.evalstr('__import__("hashlib").sha512('+
'fbuf).hexdigest().upper()'));
except
eng.raiseError;
finally
eng.Free;
end;

https://maxbox4.wordpress.com/2021/09/03/ekon-25-pypas/
Python for Delphi (I)
Imagine you need a 512bit hash (or another master of reality procedure).

● The eval() method parses the expression passed to it and runs python
expression(code) within the program.
● Exec() expects a statement, import or assignment is a statement with exec().

The eval() is not just limited to simple expression. We can execute functions, call methods,
reference variables and so on. So we use this by using the __import__() built-in function.

Note also that the computed hash is converted to a readable hexadecimal string by
hexdigest().upper()’ and uppercase the hex-values in one line, amazing isn’t it.

https://maxbox4.wordpress.com/2021/07/28/python4maxbox-code/
Python for Delphi (II)


Delphi version support
• 2009 or later (Unicode free also < D2009)

Platform support
• Windows 32 & 64 bits
• Linux
• MacOS

Mostly non-visual components
• Can be used in console applications

Lazarus/FPC/maXbox 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:\Components\P4D).

Start RAD Studio or maXbox4.

Add the source subdirectory (e.g., D:\Components\P4D\Source) 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 Packages\Delphi\Delphi 10.4+
directory. For earlier versions use the package in the Packages\Delphi\Delphi 10.3-
directory.

Note:  The package is Design & Runtime together
P4D Primer Demo

Start with a Cheatsheet:


http://www.softwareschule.ch/examples/cheatsheetpython.pdf

and a Script:
http://www.softwareschule.ch/examples/pydemo13.txt

with an Engine:
https://sourceforge.net/projects/maxbox/
SIMPLE DEMO
(I)
SynEdit

Memo
SIMPLE All components are using default properties

• PythonGUIInputOutput linked to PythonEngine and


DEMOTIVATION Memo in maXbox

(II) •
Source Code:
procedure TForm1.btnRunClick(Sender: TObject);
begin

GetPythonEngine.ExecString(UTF8Encode(sePythonC
ode.Text));
end;

http://www.softwareschule.ch/examples/pydemo29.txt
Using TPythonModule (I)

Python Delphi

def is_prime(n): function IsPrime(x: Integer): Boolean;


""" totally naive implementation """ begin
if n <= 1: if (x <= 1) then Exit(False);
return False
var q := Floor(Sqrt(x));
q = math.floor(math.sqrt(n)) for var i := 2 to q do
for i in range(2, q + 1): if (x mod i = 0) then
if (n % i == 0): Exit(False);
return False Exit(True);
return True end;
Using TPythonModule (II)
Python

def count_primes(max_n):
res = 0 Output
for i in range(2, max_n + 1): Number of primes between 0 and 1000000 = 78498
if is_prime(i): Elapsed time: 3.4528134000000037 secs
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()
Defs in P4D (III)


Add a Def() named convert as a const and link it to the PythonEngine
– ModuleName: http://www.softwareschule.ch/examples/pydemo25.txt
– Import the module with ExecStr()
• Implement python function hexconvert by writing a Pascal call

HEXCONVERT =
'""" convert hex string integer to int """ '+LF+
'def convert(n: str) -> int: '+LF+
' # get rid of ":", spaces and newlines '+LF+
' hex = n.replace(":", "").replace("\n","").replace(" ","")'+LF+
' return int(hex,16)';
Using Threads (IV)
Python

from delphi_module import delphi_is_prime


def count_primes(max_n):
res = 0 eng.Execstring('t1 =
for i in range(2, max_n + 1): threading.Thread(target=print_hello_three_times)');
if delphi_is_prime(i): eng.Execstring('t2 =
res += 1 threading.Thread(target=print_hi_three_times)');
return res eng.EvalStr('t1.start()');
eng.EvalStr('t2.start()');

const TH2 = 'def print_hi_three_times():'+LB+ Master with 2 workers!


' for i in range(3): '+LB+
println('thread target1: '+eng.EvalStr('t1'));
' print("\a") '+LB+
' winsound.Beep(440, 500) '+LB+ println('thread target2: '+eng.EvalStr('t2'));
' return "Hi"';

http://www.softwareschule.ch/examples/pydemo26.txt
Using PyTemplate (V)


Minimal Shell Configuration:

with TPythonEngine.Create(Nil) do begin


pythonhome:= PYHOME;
try
loadDLL;
Println('Decimal: '+
EvalStr('__import__("decimal").Decimal(0.1)'));
except
raiseError;
finally
free;
end;
end;
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.

You can wrap a Delphi record containing a class function.
procedure TForm1.FormCreate(Sender: TObject);
type begin
TDelphiFunctions = record var Py := PyDelphiWrapper.WrapRecord(@DelphiFunctions,
class function count_primes(MaxN: integer): integer; static; TRttiContext.Create.GetType(TypeInfo(TDelphiFunctions))
end; as TRttiStructuredType);
PythonModule.SetVar('delphi_functions', Py);
var PythonEngine.Py_DecRef(Py);
DelphiFunctions: TDelphiFunctions; end;
Conclusions


With Python for Delphi you can get the best of both worlds

P4D makes it possible to integrate Python into Delphi applications in RAD way

Expose Delphi function, objects, records and types to Python using low or high-level
interfaces

More interesting topics
• Using python libraries and objects in Delphi code like variants (VarPyth)
• Python based data analytics in Delphi applications for example TensorFlow or Pandas
Creating Python extension modules using Delphi (from delphi_module import
delphi_is_prime)

• Python GUI development using the VCL


Resources & Sources

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/

Delphi Scripter maXbox

https://sourceforge.net/projects/maxbox/

Webinar blog post
• https://blogs.embarcadero.com/python-for-delphi-developers-webinar/

You might also like