The document discusses byte-code optimization in Python. It begins by explaining that Python source code is compiled into byte code, which is then executed by the CPython interpreter. It describes some of the key steps in the compilation process, including parsing the source code and generating an abstract syntax tree (AST) before compiling to bytecodes. The document then discusses some approaches for optimizing Python code at the byte-code level, including using tools like Pyrex, Psyco and the Python bytecode manipulation library BytePlay. It recommends always profiling applications to identify optimization opportunities and considering writing performance-critical portions as C extensions.
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
This document discusses Byterun, a Python interpreter written in Python. It explains how Python code is compiled to bytecode which is then interpreted. Key points made include:
- Python code is first compiled to bytecode, which is a sequence of bytes representing operations and arguments.
- The dis module can disassemble bytecode back into a human-readable format showing the instructions.
- The interpreter works by reading each bytecode instruction and carrying out the corresponding operation, such as loading variables or performing arithmetic.
- This dynamic execution allows Python to behave differently based on the types of values at runtime, like formatting strings.
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...akaptur
Byterun is a Python interpreter written in Python with Ned Batchelder. It's architected to mirror the structure of CPython (and be more readable, too)! Learn how the interpreter is constructed, how ignorant the Python compiler is, and how you use a 1,500 line switch statement every day.
The document discusses strategies for understanding the CPython implementation of Python without reading the code. It recommends using observation and experimentation techniques like inspecting code behavior, examining commit histories, understanding internal structures through disassembly, running performance tests, and writing tests. Tools mentioned include inspect, timeit, and custom inspection modules. The key message is that these hands-on techniques allow one to critically examine and experiment with the code in ways that provide deeper understanding than just reading it.
Bytes in the Machine: Inside the CPython interpreterakaptur
This document discusses Byterun, an interpreter for Python written in Python. It explains key concepts in interpreting Python like lexing, parsing, compiling and interpreting. It describes how a Python virtual machine works using a stack and frames. It shows Python bytecode and how an interpreter executes instructions like LOAD_FAST, BINARY_MODULO, and RETURN_VALUE. It demonstrates that instructions must account for Python's dynamic nature, like strings being able to use % formatting like integers. The goal is to build an interpreter that can run Python programs directly in Python.
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...akaptur
The document discusses the inner workings of the Python virtual machine and bytecode. It explains that Python code is compiled to bytecode, which is then interpreted by a large switch statement in the Python virtual machine. The bytecode consists of numeric codes and arguments that correspond to stack-based operations. It provides examples of disassembling bytecode into a more human-readable format and how the virtual machine handles dynamic operations like string formatting and operator overloading.
The python interpreter converts programs to bytecodes before beginning execution. Execution itself consist of looping over these bytecodes and performing specific operations over each one. This talk gives a very brief overview of the main classes of bytecodes.
This presentation was given as a lightning talk at the Boston Python Meetup group on July 24th, 2012.
TCO in Python via bytecode manipulation.lnikolaeva
The document discusses optimizing tail recursion in Python by manipulating bytecode. It begins by describing the problem of recursion depth limits in Python and the challenge of optimizing recursive function calls to avoid stack overflows. It then provides an introduction to Python bytecode and disassembly and shows how a recursive function's bytecode can be modified by replacing the recursive call instruction with instructions to reset variables and jump back to the start of the function. This optimization technique is implemented in a recursion optimizer tool and shown to improve performance over the original recursive function. Further optimizations are discussed, such as tracking the call stack to properly handle calls to other functions within the recursive function.
This document discusses using the C to Go translation tool c2go to translate C code implementing quicksort algorithms into Go code. It provides examples of translating simple quicksort C code, improving the translation by using a configuration file, and how c2go handles standard C functions like qsort by translating them to their Go equivalents. The examples demonstrate how c2go can generate valid Go code from C code but may require some manual fixes or configuration to handle certain data structures or language differences.
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
This document discusses Byterun, a Python interpreter written in Python. It explains how Python code is compiled to bytecode which is then interpreted. Key points made include:
- Python code is first compiled to bytecode, which is a sequence of bytes representing operations and arguments.
- The dis module can disassemble bytecode back into a human-readable format showing the instructions.
- The interpreter works by reading each bytecode instruction and carrying out the corresponding operation, such as loading variables or performing arithmetic.
- This dynamic execution allows Python to behave differently based on the types of values at runtime, like formatting strings.
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...akaptur
Byterun is a Python interpreter written in Python with Ned Batchelder. It's architected to mirror the structure of CPython (and be more readable, too)! Learn how the interpreter is constructed, how ignorant the Python compiler is, and how you use a 1,500 line switch statement every day.
The document discusses strategies for understanding the CPython implementation of Python without reading the code. It recommends using observation and experimentation techniques like inspecting code behavior, examining commit histories, understanding internal structures through disassembly, running performance tests, and writing tests. Tools mentioned include inspect, timeit, and custom inspection modules. The key message is that these hands-on techniques allow one to critically examine and experiment with the code in ways that provide deeper understanding than just reading it.
Bytes in the Machine: Inside the CPython interpreterakaptur
This document discusses Byterun, an interpreter for Python written in Python. It explains key concepts in interpreting Python like lexing, parsing, compiling and interpreting. It describes how a Python virtual machine works using a stack and frames. It shows Python bytecode and how an interpreter executes instructions like LOAD_FAST, BINARY_MODULO, and RETURN_VALUE. It demonstrates that instructions must account for Python's dynamic nature, like strings being able to use % formatting like integers. The goal is to build an interpreter that can run Python programs directly in Python.
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...akaptur
The document discusses the inner workings of the Python virtual machine and bytecode. It explains that Python code is compiled to bytecode, which is then interpreted by a large switch statement in the Python virtual machine. The bytecode consists of numeric codes and arguments that correspond to stack-based operations. It provides examples of disassembling bytecode into a more human-readable format and how the virtual machine handles dynamic operations like string formatting and operator overloading.
The python interpreter converts programs to bytecodes before beginning execution. Execution itself consist of looping over these bytecodes and performing specific operations over each one. This talk gives a very brief overview of the main classes of bytecodes.
This presentation was given as a lightning talk at the Boston Python Meetup group on July 24th, 2012.
TCO in Python via bytecode manipulation.lnikolaeva
The document discusses optimizing tail recursion in Python by manipulating bytecode. It begins by describing the problem of recursion depth limits in Python and the challenge of optimizing recursive function calls to avoid stack overflows. It then provides an introduction to Python bytecode and disassembly and shows how a recursive function's bytecode can be modified by replacing the recursive call instruction with instructions to reset variables and jump back to the start of the function. This optimization technique is implemented in a recursion optimizer tool and shown to improve performance over the original recursive function. Further optimizations are discussed, such as tracking the call stack to properly handle calls to other functions within the recursive function.
This document discusses using the C to Go translation tool c2go to translate C code implementing quicksort algorithms into Go code. It provides examples of translating simple quicksort C code, improving the translation by using a configuration file, and how c2go handles standard C functions like qsort by translating them to their Go equivalents. The examples demonstrate how c2go can generate valid Go code from C code but may require some manual fixes or configuration to handle certain data structures or language differences.
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
The document discusses various techniques for iteration in Python. It covers iterating over lists, dictionaries, files and more. It provides examples of iterating properly to avoid errors like modifying a list during iteration. Context managers are also discussed as a clean way to handle resources like file objects. Overall the document shares best practices for writing efficient and robust iteration code in Python.
В последнее время экосистема .NET развивается очень динамично: постоянно появляются новые технологии и инструменты, а старые обзаводятся новыми возможностями. Уследить за всем очень сложно, поэтому в этом докладе мы постараемся обзорно взглянуть на текущее состояние платформы .NET, а также на то, что нас ждёт в ближайшем будущем. Будем говорить про грядущий C#7, про кроссплатформенность и нативную компиляцию, про новый .NET Core 5 и ASP.NET 5, про новые инструменты для разработчиков и последние анонсы от Microsoft.
Implementing Software Machines in C and GoEleanor McHugh
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
Elixir is a functional programming language that is well-suited for building scalable and fault-tolerant applications. The document provides an introduction to Elixir by discussing its roots in Erlang and how it builds upon Erlang's strengths like concurrency, distribution, and fault tolerance. It also demonstrates some basic Elixir concepts like functions, pattern matching, recursion, and the BEAM virtual machine. Finally, it provides examples of real-world applications of Elixir like building Phoenix web applications and developing embedded hardware projects with Nerves.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrainsit-people
The document discusses debugging in Python 3.6. It describes tracing and frame evaluation debuggers. Tracing debuggers slow code execution significantly by calling the tracing function on every line. Python 3.6 introduced a new frame evaluation API that allows evaluating frames directly, avoiding the performance issues of tracing. The document demonstrates how to build a debugger using this approach, including setting breakpoints and stepping through code by inserting temporary breakpoints on each line. Frame evaluation allows building a debugger that is faster than tracing debuggers without significant performance penalties.
This document summarizes two projects that aim to optimize Python performance: the AST optimizer and register-based bytecode. The AST optimizer rewrites Python abstract syntax trees to enable more optimizations than CPython's peephole optimizer. It aims to improve performance by constant folding, loop optimizations, and other transformations. The register-based bytecode project rewrites CPython's stack-based bytecode to use registers, enabling additional optimizations like common subexpression elimination and constant/attribute deduplication. Both projects showed speedups over CPython in benchmarks, but may not translate to all real applications. The document provides details on each project's approach and goals.
Implementing Software Machines in Go and CEleanor McHugh
Early draft of a tutorial on techniques for implementing virtual machines and language interpreters. Contains example programs for functional stacks and despatch loops.
Не так давно вышел C# 6, основанный на новом компиляторе Roslyn. Обновление языка содержит большое количество приятных синтаксических конструкций, которые упрощают написание кода и делают его более лаконичным. Но Microsoft на этом не успокоились: прямо сейчас ведётся работа над 7-ой версией языка, которую планируют сделать ещё удобнее, благодаря реализации современных тенденций написания кода. В этом докладе мы поговорим о том, что может войти в C# 7. В числе прочего будут обсуждаться Tuples, Pattern matching, Records / algebraic data types, Nullability tracking и многое другое.
The document provides an overview of the Go programming language, including its history, data types, basic syntax like variables and functions, and common constructs like arrays, slices, maps, and concurrency features. It was developed at Google in 2009 and aims to provide efficiency of static typing with ease of dynamic languages through features like garbage collection and good support for concurrency and communication.
This document provides an introduction and overview to the Python programming language. It includes sections on why learn programming and Python, how to learn Python, Python versions 2 vs 3, data types in Python like integers, floats, strings, lists, dictionaries, functions, loops, and classes. The document contains links to online resources for learning Python and examples of basic Python code.
The document discusses C++ and its history and features. It describes C++ as an extension of C with object-oriented features like classes. It provides information on the creator of C++, Bjarne Stroustrup, and the evolution of C++ since its introduction as a way to add object-oriented programming to C. It also includes sample C++ code demonstrating the use of arrays and includes from the Boost library.
The document summarizes various Python profiling tools. It discusses using the time utility and time module to measure elapsed time. It also covers the profile, cProfile, hotshot, lineprofiler, memoryprofiler, and objgraph modules for profiling code performance and memory usage. Examples are given showing how each tool can be used and the type of output it provides.
The document provides an overview of buffer overflow vulnerabilities including:
1) It explains how buffer overflows work by writing more data to a buffer than it was allocated to hold, overwriting adjacent memory.
2) An example is given of a function that is vulnerable to buffer overflow by copying user input into a fixed-size buffer without checks.
3) It shows how by passing too much input data, the buffer can be overflown and the return address on the stack overwritten to point to the injected data instead of the intended return location.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
Metarhia is a technology stack and community for building distributed, high-load applications and data storage. It includes an Impress application server, the JSTP protocol, GlobalStorage distributed database, and other tools. The goals of Metarhia include unifying APIs, data, and contracts across server infrastructure with an open source approach and no vendor lock-in. Key people behind Metarhia include Timur Shemsedinov and Alexey Orlenko, who are both Node.js contributors and open source advocates.
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Why we are submitting this talk? Because Go is cool and we would like to hear more about this language ;-). In this talk we would like to tell you about our experience with development of microservices with Go. Go enables devs to create readable, fast and concise code, this - beyond any doubt is important. Apart from this we would like to leverage our test driven habbits to create bulletproof software. We will also explore other aspects important for adoption of a new language.
The document discusses JIT compilation in CPython. It begins with a brief history of JIT compilation, including early implementations in LISP and Smalltalk. The author then describes their experience with JIT compilation in CPython, including converting Python code to IL assembly and machine code. Benchmarks show the JIT compiled Fibonacci function is around 8 times faster than the unoptimized version. Finally, the document briefly mentions the Numba project, which uses JIT compilation to accelerate Python code.
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
The document discusses various techniques for iteration in Python. It covers iterating over lists, dictionaries, files and more. It provides examples of iterating properly to avoid errors like modifying a list during iteration. Context managers are also discussed as a clean way to handle resources like file objects. Overall the document shares best practices for writing efficient and robust iteration code in Python.
В последнее время экосистема .NET развивается очень динамично: постоянно появляются новые технологии и инструменты, а старые обзаводятся новыми возможностями. Уследить за всем очень сложно, поэтому в этом докладе мы постараемся обзорно взглянуть на текущее состояние платформы .NET, а также на то, что нас ждёт в ближайшем будущем. Будем говорить про грядущий C#7, про кроссплатформенность и нативную компиляцию, про новый .NET Core 5 и ASP.NET 5, про новые инструменты для разработчиков и последние анонсы от Microsoft.
Implementing Software Machines in C and GoEleanor McHugh
The next iteration of the talk I gave at Progscon, this introduces examples of Map implementation (useful for caches etc.) and outlines for addition of processor core code in a later talk.
Elixir is a functional programming language that is well-suited for building scalable and fault-tolerant applications. The document provides an introduction to Elixir by discussing its roots in Erlang and how it builds upon Erlang's strengths like concurrency, distribution, and fault tolerance. It also demonstrates some basic Elixir concepts like functions, pattern matching, recursion, and the BEAM virtual machine. Finally, it provides examples of real-world applications of Elixir like building Phoenix web applications and developing embedded hardware projects with Nerves.
A reworking of my 2010 RubyConf lightning talk introducing Go via a concurrent implementation of MapReduce. This code is probably buggy as hell and the design awful but it's also a reasonably good intro to the full breadth of Go.
«Отладка в Python 3.6: Быстрее, Выше, Сильнее» Елизавета Шашкова, JetBrainsit-people
The document discusses debugging in Python 3.6. It describes tracing and frame evaluation debuggers. Tracing debuggers slow code execution significantly by calling the tracing function on every line. Python 3.6 introduced a new frame evaluation API that allows evaluating frames directly, avoiding the performance issues of tracing. The document demonstrates how to build a debugger using this approach, including setting breakpoints and stepping through code by inserting temporary breakpoints on each line. Frame evaluation allows building a debugger that is faster than tracing debuggers without significant performance penalties.
This document summarizes two projects that aim to optimize Python performance: the AST optimizer and register-based bytecode. The AST optimizer rewrites Python abstract syntax trees to enable more optimizations than CPython's peephole optimizer. It aims to improve performance by constant folding, loop optimizations, and other transformations. The register-based bytecode project rewrites CPython's stack-based bytecode to use registers, enabling additional optimizations like common subexpression elimination and constant/attribute deduplication. Both projects showed speedups over CPython in benchmarks, but may not translate to all real applications. The document provides details on each project's approach and goals.
Implementing Software Machines in Go and CEleanor McHugh
Early draft of a tutorial on techniques for implementing virtual machines and language interpreters. Contains example programs for functional stacks and despatch loops.
Не так давно вышел C# 6, основанный на новом компиляторе Roslyn. Обновление языка содержит большое количество приятных синтаксических конструкций, которые упрощают написание кода и делают его более лаконичным. Но Microsoft на этом не успокоились: прямо сейчас ведётся работа над 7-ой версией языка, которую планируют сделать ещё удобнее, благодаря реализации современных тенденций написания кода. В этом докладе мы поговорим о том, что может войти в C# 7. В числе прочего будут обсуждаться Tuples, Pattern matching, Records / algebraic data types, Nullability tracking и многое другое.
The document provides an overview of the Go programming language, including its history, data types, basic syntax like variables and functions, and common constructs like arrays, slices, maps, and concurrency features. It was developed at Google in 2009 and aims to provide efficiency of static typing with ease of dynamic languages through features like garbage collection and good support for concurrency and communication.
This document provides an introduction and overview to the Python programming language. It includes sections on why learn programming and Python, how to learn Python, Python versions 2 vs 3, data types in Python like integers, floats, strings, lists, dictionaries, functions, loops, and classes. The document contains links to online resources for learning Python and examples of basic Python code.
The document discusses C++ and its history and features. It describes C++ as an extension of C with object-oriented features like classes. It provides information on the creator of C++, Bjarne Stroustrup, and the evolution of C++ since its introduction as a way to add object-oriented programming to C. It also includes sample C++ code demonstrating the use of arrays and includes from the Boost library.
The document summarizes various Python profiling tools. It discusses using the time utility and time module to measure elapsed time. It also covers the profile, cProfile, hotshot, lineprofiler, memoryprofiler, and objgraph modules for profiling code performance and memory usage. Examples are given showing how each tool can be used and the type of output it provides.
The document provides an overview of buffer overflow vulnerabilities including:
1) It explains how buffer overflows work by writing more data to a buffer than it was allocated to hold, overwriting adjacent memory.
2) An example is given of a function that is vulnerable to buffer overflow by copying user input into a fixed-size buffer without checks.
3) It shows how by passing too much input data, the buffer can be overflown and the return address on the stack overwritten to point to the injected data instead of the intended return location.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
Metarhia is a technology stack and community for building distributed, high-load applications and data storage. It includes an Impress application server, the JSTP protocol, GlobalStorage distributed database, and other tools. The goals of Metarhia include unifying APIs, data, and contracts across server infrastructure with an open source approach and no vendor lock-in. Key people behind Metarhia include Timur Shemsedinov and Alexey Orlenko, who are both Node.js contributors and open source advocates.
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
An updated version of my talk on virtual machine cores comparing techniques in C and Go for implementing dispatch loops, stacks & hash maps.
Lots of tested and debugged code is provided as well as references to some useful/interesting books.
Why we are submitting this talk? Because Go is cool and we would like to hear more about this language ;-). In this talk we would like to tell you about our experience with development of microservices with Go. Go enables devs to create readable, fast and concise code, this - beyond any doubt is important. Apart from this we would like to leverage our test driven habbits to create bulletproof software. We will also explore other aspects important for adoption of a new language.
The document discusses JIT compilation in CPython. It begins with a brief history of JIT compilation, including early implementations in LISP and Smalltalk. The author then describes their experience with JIT compilation in CPython, including converting Python code to IL assembly and machine code. Benchmarks show the JIT compiled Fibonacci function is around 8 times faster than the unoptimized version. Finally, the document briefly mentions the Numba project, which uses JIT compilation to accelerate Python code.
This document provides an overview of the bonobo Python library for simple ETL (extract, transform, load) workflows. It discusses the history and concepts of ETL, demonstrates basic usage of bonobo to define extract, transform, and load functions in a graph, and outlines the library's future plans, which include adding support for scheduling, monitoring, and more execution strategies. The goal of bonobo is to provide a Pythonic way to write ETL jobs using code as configuration in a simple and testable way.
Pysense: wireless sensor computing in Python?Davide Carboni
PySense aims at bringing wireless sensor (and "internet of things") macroprogramming to the audience of Python programmers. WSN macroprogramming is an emerging approach where the network is seen as a whole and the programmer focuses only on the application logic. The PySense runtime environment
partitions the code and transmits code snippets to the right nodes finding a balance between energy
consumption and computing performances.
This presentation is about using Boost.Python library to create modules with С++.
Presentation by Andriy Ohorodnyk (Lead Software Engineer, GlobalLogic, Lviv), delivered GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
The document discusses how Python code is executed. It explains that Python code is first compiled into code objects then executed via a frame object on the stack. Code objects contain details like function names and constants while frame objects contain details like the current code, local and global variables. It also describes the main components involved in execution like opcodes, bytecodes, and the CPython interpreter which evaluates bytecodes by calling corresponding operations.
The document discusses finding and analyzing iOS kernel bugs through fuzzing techniques. It begins by providing background on the iOS kernel structure based on XNU and OSX. It then summarizes two known iOS kernel bugs from the past that involved integer overflows and type conversions. The document goes on to describe passive and active fuzzing approaches that can be used to find new bugs, including hooking kernel functions to fuzz parameters. It also provides tips on reversing iOS kernel extensions and debugging the kernel. Finally, it analyzes examples of bugs found through fuzzing and how to understand the crash causes and trigger paths through static analysis and debugging.
Notes about moving from python to c++ py contw 2020Yung-Yu Chen
The document discusses moving from Python to C++. It notes that Python is commonly used for application development due to its ease of use, while C++ is used for high-performance computing kernels due to better performance. It recommends binding Python and C++ together, using C++ for performance critical parts and Python for user interfaces and scripting. Pybind11 is identified as a good tool for binding Python and C++ that provides modern C++ features and is easy to use.
The document discusses the JavaScript engine architecture in SpiderMonkey. It describes the roles of the interpreter, baseline just-in-time (JIT) compiler, and IonMonkey JIT compiler. The interpreter parses JavaScript code into bytecode, which is then run by interpreting and invoking C++ functions. The baseline JIT compiles hot bytecode into optimized assembly code. IonMonkey performs a full optimization of JavaScript functions by compiling them into a graph representation. Bailouts can occur if type assumptions made during JIT compilation turn out to be incorrect.
英文【Xu hao chen xiaobo】find your_own_ios_kernel_bugWang Hao Lee
The document provides guidance on finding kernel bugs in iOS through fuzzing techniques. It begins with background on the iOS kernel architecture and known bugs. It then discusses passive fuzzing by hooking IOKit interfaces and active fuzzing by programmatically testing IOKit driver methods. The document demonstrates analyzing two example crashes to understand the bugs through static analysis and reverse engineering techniques when debug is difficult. The conclusion encourages fuzzing to find new bugs and improving kernel code quality.
This document discusses different approaches for creating Python extensions and bindings to C/C++ libraries. It summarizes the author's experience using ctypes to create a minimal binding called PyMiniRacer to the V8 JavaScript engine. The author argues that combining ctypes, which allows shipping a single Python-independent binary, with pre-built wheel distributions can provide an optimal solution for packaging and distributing Python extensions.
This document provides an overview of how to contribute to the cPython source code. It discusses running benchmarks to understand performance differences between loops inside and outside functions. It encourages contributing to improve coding skills and help the open source community. The steps outlined are to clone the cPython source code repository, resolve any dependencies during building, review open issues on bugs.python.org, and work on resolving issues - starting with easier ones. Tips are provided such as commenting when taking ownership of an issue, reproducing bugs before working on them, writing tests for code changes, and updating documentation.
MPI provides collective communication operations that involve all processes in a communicator. These include broadcast to distribute data from one process to all others, scatter and gather to divide and combine data across processes, allgather to collect all data from processes, and alltoall to fully exchange portions of data between all process pairs. Collective operations synchronize processes and can be used to solve many parallel algorithms and computational problems.
Modern binary build systems have made shipping binary packages for Python much easier than ever before. This talk discusses three of the most popular build systems for Python packages using the new standards developed for packaging.
Python was developed by Guido van Rossum and named after the BBC show Monty Python's Flying Circus. It is an interpreted, interactive, and object-oriented programming language that allows developers to write code in fewer lines compared to other languages. Python code is highly readable due to its use of indentation instead of brackets and its support for modular programming.
PyCon KR 2019 sprint - RustPython by exampleYunWon Jeong
The document describes finding and fixing a bug in the RustPython interpreter. Specifically, there was a bug where the divmod() function was not properly handling negative numbers. The steps taken to address this were:
1. Reproducing the bug by running an import datetime statement
2. Debugging the divmod() implementation
3. Adding a new test case to validate the expected output of divmod(-86340, 86400)
4. Fixing the divmod() implementation directly in the ObjInt source code
5. Creating a pull request on GitHub to submit the fixes
Talk at PyCon2022 over building binary packages for Python. Covers an overview and an in-depth look into pybind11 for binding, scikit-build for creating the build, and build & cibuildwheel for making the binaries that can be distributed on PyPI.
Cleanup and new optimizations in WPython 1.1PyCon Italia
This document summarizes optimizations and cleanup made to the WPython interpreter in version 1.1. Key changes include removing an unnecessary type object "hack" from version 1.0, fixing tracing for optimized loops, removing redundant checks and opcodes, adding new opcode functions, and implementing specialized opcodes for common patterns like comparisons.
Cython allows Python code to be compiled to C/C++ extensions for improved performance. It is a superset of Python that adds static type declarations for variables and functions. This allows Cython code to be compiled to efficient C/C++ code while retaining the syntax and functionality of Python. The document provides an overview of Cython and examples demonstrating how to install Cython, write basic Cython modules, optimize Python code with static types, call C functions from Cython, and interface with C/C++ libraries.
This document describes CorePy, a library for Cell/B.E. programming from Python. CorePy allows developers to execute arbitrary SPE programs from Python and talk to SPE programs using wrappers. It provides components for execution management, code synthesis, and instruction set support. CorePy aims to increase productivity for multi-core and SIMD programming while providing direct hardware access. Examples show how to parallelize algorithms like population count using CorePy and synthetic programming techniques.
Similar to Diving into byte code optimization in python (20)
Rapid development & integration of real time communication in websitesChetan Giridhar
This document discusses how real-time communication can be rapidly developed and integrated into websites using Python. It provides an overview of key considerations for building live chat features, demonstrates using Python and Tornado to create a live chat application, and discusses the business benefits of integrating real-time communication into websites.
The document provides an overview of asynchronous programming in Python. It discusses how asynchronous programming can improve performance over traditional synchronous and threaded models by keeping resources utilized continuously. It introduces key concepts like callbacks, coroutines, tasks and the event loop. It also covers popular asynchronous frameworks and modules in Python like Twisted, Tornado, gevent and asyncio. Examples are provided to demonstrate asynchronous HTTP requests and concurrent factorial tasks using the asyncio module. Overall, the document serves as an introduction to asynchronous programming in Python.
PyCon India 2012: Rapid development of website search in pythonChetan Giridhar
The document discusses developing website search capabilities in Python. It provides an overview of typical search engine components like indexing, analyzing, and searching. It then compares two Python search libraries - Pylucene and Whoosh. Benchmark tests on indexing, committing, and searching a 1GB dataset showed Whoosh to outperform Pylucene in speed. The document recommends designing search as an independent, pluggable component and considers Whoosh and Pylucene as good options for rapid development and integration into Python web projects.
Fuse'ing python for rapid development of storage efficient FSChetan Giridhar
FUSE allows developers to create file systems in userspace without writing kernel code. It provides a virtual filesystem layer that intercepts system calls and redirects them to a userspace program. The seFS prototype uses FUSE to create an experimental file system that provides online data deduplication and compression using SQLite for storage. It demonstrates how FUSE enables rapid development of new file systems in Python by treating them as regular applications instead of kernel modules.
Testers in product development code review phaseChetan Giridhar
Testers reviewing developer code can break myths and provide quality benefits. Code reviews allow testers to find defects early, improve testing documentation, and better understand implementations versus specifications. While there is a learning curve, code reviews improve rapport between developers and testers by utilizing different perspectives. Overall, code reviews are worth trying as both developers and testers can provide inputs that improve the product if given time to realize dividends.
The Model-View-Controller (MVC) pattern separates an application into three main components: the model, the view, and the controller. The sample Python implementation demonstrates an MVC pattern for a test management system with a SQLite database. The DefectModel class represents the model component and interacts with the database. The controller handles user requests and interacts with the model and view components. The view is responsible for displaying the results to the user.
This tutorial provides an introduction to the Python programming language. It will cover Python's core features like syntax, data types, operators, conditional and loop execution, functions, modules and packages to enable writing basic programs. The tutorial is intended for learners to learn Python together through questions, discussions and pointing out mistakes.
PyCon India 2011: Python Threads: Dive into GIL!Chetan Giridhar
This document discusses the Global Interpreter Lock (GIL) in Python and how it impacts multithreading.
The GIL ensures that only one Python thread can execute at a time. This prevents true concurrency on multicore systems. It also leads to issues like priority inversion and the "convoy effect" where I/O-bound threads can be starved by CPU-bound threads.
Python 3.2 improved the GIL by introducing a timeout, but a performance dip is still seen on multicore systems compared to single core. Alternatives like Jython (GIL-free) and multiprocessing can better utilize multiple cores.
This document summarizes a presentation about Python threads and the Global Interpreter Lock (GIL). It discusses how the GIL provides synchronization for Python's memory management but prevents true concurrency. It describes how the GIL is implemented and how it is managed through "checks" and tick counts. It also covers how the new GIL in Python 3.2 aims to improve fairness on multicore systems through a timeout mechanism. Finally, it discusses alternatives like Jython, multiprocessing, and Stackless Python that can better utilize multiple CPU cores.
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxSitimaJohn
Ocean Lotus cyber threat actors represent a sophisticated, persistent, and politically motivated group that poses a significant risk to organizations and individuals in the Southeast Asian region. Their continuous evolution and adaptability underscore the need for robust cybersecurity measures and international cooperation to identify and mitigate the threats posed by such advanced persistent threat groups.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Project Management Semester Long Project - Acuityjpupo2018
Acuity is an innovative learning app designed to transform the way you engage with knowledge. Powered by AI technology, Acuity takes complex topics and distills them into concise, interactive summaries that are easy to read & understand. Whether you're exploring the depths of quantum mechanics or seeking insight into historical events, Acuity provides the key information you need without the burden of lengthy texts.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
Webinar: Designing a schema for a Data WarehouseFederico Razzoli
Are you new to data warehouses (DWH)? Do you need to check whether your data warehouse follows the best practices for a good design? In both cases, this webinar is for you.
A data warehouse is a central relational database that contains all measurements about a business or an organisation. This data comes from a variety of heterogeneous data sources, which includes databases of any type that back the applications used by the company, data files exported by some applications, or APIs provided by internal or external services.
But designing a data warehouse correctly is a hard task, which requires gathering information about the business processes that need to be analysed in the first place. These processes must be translated into so-called star schemas, which means, denormalised databases where each table represents a dimension or facts.
We will discuss these topics:
- How to gather information about a business;
- Understanding dictionaries and how to identify business entities;
- Dimensions and facts;
- Setting a table granularity;
- Types of facts;
- Types of dimensions;
- Snowflakes and how to avoid them;
- Expanding existing dimensions and facts.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Diving into byte code optimization in python
1. Diving into Byte-code
optimization in Python
SciPy India,
IIT Bombay Dec 05th 2011
Chetan Giridhar and Vishal Kanaujia
2. Fundamentals of Bytecode
• Python source code compiled into Python
byte code by the CPython interpreter
• “.pyc”?
– Automatic compilation : importing a module
– Explicit compilation :
py_compile.compile(“module.py”) – generates
‘module.pyc’
• The module ‘compileall’{}
Attribution-NonCommercial CC BY-NC
3. Fundamentals | more
• A program doesn't run any faster when it is
read from a ‘.pyc’ file. But, why?
• “.pyc” for a script executed on the command
line
• “.pyc” files – good enough to distribute your
code, but with a caveat!
Attribution-NonCommercial CC BY-NC
4. Compilation phases
• Uses a ‘lexer’ to prepare tokens of Python
code
• A parser arranges token according to the
language grammar and prepares concrete
syntax tree
• Concrete syntax tree is transformed in to AST
• AST is compiled to produce Byte-codes
Attribution-NonCommercial CC BY-NC
5. Python Abstract
Parse Tree
source Syntax
generated
code Tree
Pgen.c
ast.c
compile.c
Executed
Optimized Bytecode
by Python
bytecode generated
VM
ceval.c peephole.c
6. Python “ast” module
$ cat myast.py $python myast.py
<generator object walk at 0xb784c8ec>
import ast
Module(body=[Expr(value=BinOp
nod = ast.parse('a +2') (left=Name(id='a', ctx=Load()),
print ast.walk(nod) op=Add(),
right=Num(n=2)))])
print ast.dump(nod)
•Convenient for analysis, code transformations and generation
•ASTs are compiled to code objects
Attribution-NonCommercial CC BY-NC
7. A peek into Bytecodes
$ cat scipy.py $ python scipy.py
1 import dis 4 0 LOAD_CONST 1 (10)
3 STORE_FAST 0 (i)
2
3 def foo(): 5 6 LOAD_FAST 0 (i)
9 PRINT_ITEM
4 i = 10 10 PRINT_NEWLINE
5 print i 11 LOAD_CONST 0 (None)
14 RETURN_VALUE
6
7 print dis.dis(foo)
• Bytecode stream: An opcode mix
• Defined in “Python-2.7.2/Include/opcode.h”
Attribution-NonCommercial CC BY-NC
8. Python VM
• Engine to execute Bytecodes
• CPython VM is a C implementation
• Stack based process VM
– PUSH/ POP operations
• Implementation of Python VM?
Attribution-NonCommercial CC BY-NC
9. Python VM: Implementation
Python/ceval.c
--> PyEval_EvalFrameEx()
for(; ;) {
/* Extract opcode and argument */
opcode = NEXTOP();
if (HAS_ARG(opcode))
oparg = NEXTARG();
switch(opcode) {
case LOAD_CONST:
……
}
}
Attribution-NonCommercial CC BY-NC
10. Optimizations
Tools
Getting in to the Problem Space!!
Attribution-NonCommercial CC BY-NC
11. Pyrex
• Python like language to create C module for
Python
• Create your “pyx” files and compile them in “.c”
files
• Import them as modules in your applications
• Pyrex used as:
– speed up the execution of Python code
– Python interface to existing C modules/libraries
• Lot of work for developer
– .py to .pyx?
– thinking in C
Attribution-NonCommercial CC BY-NC
12. Psyco
• An intelligent option – JIT compilation
• Profiles dynamically an application for hot-
spots
• “in-memory” prepares C extension and hook
them appropriately
• Solves “duck” typing
• Memory footprint?
• Support till CPython 2.5
Attribution-NonCommercial CC BY-NC
13. Psyco| Intelligent use
Iterations Without With
Pysco(ms) Pysco(ms)
1000 125 151
100000 12900 12570
• from psyco.classes import *
• pysco.bind(func)
Attribution-NonCommercial CC BY-NC
14. Optimizations
Bytecode level
Getting in to the Problem Space!!
Attribution-NonCommercial CC BY-NC
16. Optimizations: Tail Recursive Calls
$ cat runbytecode3.py $ python runbytecode3.py
import dis 5 1 LOAD_CONST 10
2 STORE_FAST x
6 4 LOAD_FAST x
def foo(): 5 LOAD_CONST 10
x = 10 6 COMPARE_OP ==
7 POP_JUMP_IF_FALSE to 17
if x == 10:
7 9 LOAD_CONST 0
x=0 10 STORE_FAST x
foo()
8 12 LOAD_GLOBAL foo
13 CALL_FUNCTION 0
14 POP_TOP
print dis.dis(foo) 15 JUMP_FORWARD to 17
>> 17 LOAD_CONST None
18 RETURN_VALUE
None
Attribution-NonCommercial CC BY-NC
17. BytePlay: Do it yourself!
• Experiment with Bytecodes
• Generates, recompiles and runs code on-the-
fly
• Very useful to evaluate different code
optimizations
• Example
Attribution-NonCommercial CC BY-NC
18. Playing with Bytecode
$cat runbytecode2.py $ python runbytecode2.py
reassembled ‘byteplay.py' imported.
from byteplay import *
from pprint import pprint 5 1 LOAD_CONST 10 <<<-------------------------
2 STORE_FAST x
def foo():
x = 10 6 4 LOAD_FAST x
5 PRINT_ITEM
print x
6 PRINT_NEWLINE
7 LOAD_CONST None
c = Code.from_code(foo.func_code) 8 RETURN_VALUE
print printcodelist(c.code) None
# Modify the byte code 5 1 LOAD_CONST 1000 <<<---------------------------
c.code[0] = (LOAD_CONST, 1000) 2 STORE_FAST x
foo.func_code = c.to_code() 6 4 LOAD_FAST x
5 PRINT_ITEM
print printcodelist(c.code) 6 PRINT_NEWLINE
7 LOAD_CONST None
8 RETURN_VALUE
# Call the modified function
None
foo()
1000
Attribution-NonCommercial CC BY-NC
19. Going forward
PyPy
Getting in to the Problem Space!!
Attribution-NonCommercial CC BY-NC
20. Does PyPy help?
• Python interpreter in Python itself
• A target function needs to be written with
subset of Python (Restricted Python)
• PyPy can translate this function to runtime of
your choice ☺
– Options: C/POSIX, CLI/.NET and Java/JVM
• Seamless and transparent
Attribution-NonCommercial CC BY-NC
21. PyPy | more
from pypy.translator.interactive import @compdec
Translation
def fact(n):
class compdec:
if 0 == n:
def __init__(self, func): return 1
self.func = func return n * fact(n -1)
self.argtypes = None fact(10)
def __call__(self, *args):
argtypes = tuple(type(arg) for arg in
args)
if argtypes != self.argtypes:
self.argtypes = argtypes
t = Translation(self.func)
t.annotate(argtypes)
self.cfunc = t.compile_c() What PyPy does?
•The translation of the RPython function to C.
•Invoking the C compiler to create a C extension module.
return self.cfunc(*args)
•Importing the compiled function back into the Python interpreter.
Attribution-NonCommercial CC BY-NC
22. Recommendations
• Always profile your applications
• 90/10 rule of performance gain
• Performance critical portion could be written
as C extensions
– Wrappers like SWIG could be used to bridge
Python/C applications
– Pyrex, Psyco, and PyPy
– Tuning Bytecodes manually
• Evaluate and use ☺
Attribution-NonCommercial CC BY-NC
24. Questions
Thank you for your time and attention ☺
• Please share your feedback/ comments/ suggestions to us at:
• cjgiridhar@gmail.com , http://technobeans.com
• vishalkanaujia@gmail.com, http://freethreads.wordpress.com
Attribution-NonCommercial CC BY-NC
26. Bytecodes | more
• Atomic unit of execution (thread safe)
• A Python module is compiled and saved in
form of a “pyc” file
• An optimization; avoid compilation phase for
future uses of a module
• If source file is changed, pyc is recompiled
• “pyc” file is coded in bytecode!
Attribution-NonCommercial CC BY-NC
27. Code Objects
• Bytecode representation
• Immutable objects (No ref to mutable objects)
• Function object (Code objects that reference
global variables)
• “co_code” = Bytecodes
Attribution-NonCommercial CC BY-NC
28. Benefits of using Bytecode
• Architecture neutral code
• Portability
• Simple optimizations
Attribution-NonCommercial CC BY-NC