EKON 25 Python4Delphi MX4
EKON 25 Python4Delphi MX4
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
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
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
•
(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 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
http://www.softwareschule.ch/examples/pydemo26.txt
Using PyTemplate (V)
•
Minimal Shell Configuration:
•
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)