SCRIPTING I/III EXTENDING PYTHON. References:

Size: px
Start display at page:

Download "SCRIPTING I/III EXTENDING PYTHON. References:"

Transcription

1 SCRIPTING I/III EXTENDING PYTHON References:

2 GOALS Part I: Create a module (a C dll), callable from python [extension] Functions Class (with methods) Illustrate type conversions Introduce reference counting Part II: Create a python interpreter embedded in a C program. Coordinate python scripts and C functionality Part III: [?] Embed into our larger project. Make a (partial) mirror of our C GameObject in Python.

3 PYTHON C API OVERVIEW A massive collection of C (not C++) functions Naming conventions: Py_XXX: where XXX is a top-level function PyYYY_ZZZ: where YYY is a python type and ZZZ is the method. E.g. PyTuple_GetSize PyObject: nearly everything uses (and is one of) these primitives: int, floats complex primitives: strings, lists, tuples functions classes (and instances) modules exceptions You have to check the type (PyYYY_Check(PyObject*)). A lot of our work involves converting C <-> Python data

4 FIRST STEPS C code Python code DLL release 1 project (I'm calling mine testmod) Include directories = "%PythonHome\include" Library directories = "%PythonHome\libs" Input is "Python3.lib" (more limited, but usable on python 3.x) or "Python33.lib" (has any 3.3-specific functionality) Change name of extension to pyd Put any test python code next to the.pyd file. In this section, we'll run python code with the normal interpreter (PyCharm, Idle, cmd-line all OK) 1. Unless you build python from source, you're using a release build (so our dll has to be release as well)

5 PART I: MODULE CREATIONS + FUNCTION Warning: I know you could just zip through this lecture and copypaste. I suggest, however, that you do it with us I'll try to add running commentary as we go that will (hopefully) help you better understand it. Ask questions as we go through this!!

6 CREATING THE MODULE #include <Python.h> static struct PyModuleDef testmod_definition = PyModuleDef_HEAD_INIT, "testmod", "My super-awesome first python extension", -1, NULL }; PyMODINIT_FUNC PyInit_testMod(void) PyObject * mod = PyModule_Create(&testMod_definition); return mod; }

7 TESTING THE MODULE import testmod print("testmod. name = " + testmod. name ) print("testmod. doc = " + testmod. doc ) print(dir(testmod))

8 TANGENT: REFERENCE-COUNTING AND GARBAGE COLLECTION INTRO L = [["a", 4.7], ["b", 1.1]] # RC on all are 1 L[0] = ["c", 9.2] # RC on "a" dropped to # 0 GC G = L # RC on main list is 2 H = L[1] # RC on "b" is 2 L = "hi!" # RC on main list is 1 G = "bye!" # RC on main list is 0 GC # "b" has RC of 1 # so no GC H = "hasta la vista" # Now "b" has RC of 0 - GC

9 ADDING CONSTANTS (For example math.pi in the built-in math module) PyObject * mod = PyModule_Create(&testMod_definition); if (mod == NULL) return NULL; // Add a (totally pointless) integer constant to the module // You'll need PyModule_??? [Finish me] import testmod print("testmod.mysteryvalue = " + str(testmod.mysteryvalue))

10 ADDING A FUNCTION (GOAL) # We want to add this functionality to the module: # (as before) T = testmod.buildtuple(6, 0.3, 1) print(t) # A tuple of 6 floats in range # I was the last two params to be either # floats or int (any number type) # These should cause an error # T = testmod.buildtuple(3) # Too few parameters # T = testmod.buildtuple(6, 1.4, 1.2) # max before min

11 ADDING A FUNCTION (IMPLEMENTATION) static PyObject * testmod_buildtuple(pyobject * self, PyObject * args) if (!PyTuple_Check(args) PyTuple_Size(args)!= 3!PyLong_Check(PyTuple_GetItem(args, 0))!PyNumber_Check(PyTuple_GetItem(args, 1))!PyNumber_Check(PyTuple_GetItem(args, 2))) PyErr_SetString(PyExc_ValueError, "You must pass an int (num elements) and two floats (min & max)"); return NULL; } // Actually extract the parameters from the tuple. int num_elem = PyLong_AsLong(PyTuple_GetItem(args, 0)); PyObject * first_num = PyNumber_Float(PyTuple_GetItem(args, 1)); PyObject * second_num = PyNumber_Float(PyTuple_GetItem(args, 2)); double min_val = PyFloat_AsDouble(first_num); double max_val = PyFloat_AsDouble(second_num); Py_DECREF(first_num); Py_DECREF(second_num); if (min_val > max_val) PyErr_SetString(PyExc_ValueError, "The min-value must be smaller (or equal to) the max value"); return NULL; }

12 ADDING A FUNCTION (IMPLEMENTATION) continuation of testmod_buildtuple from last slide // Create and fill the tuple. // I want you to figure this part out. You'll likely need the // following functions: PyTuple_New, PyTuple_SetItem and PyFloat_??? [FINISH ME] }

13 ADDING A FUNCTION (IMPLEMENTATION) // Add this line to PyInit_testMod srand(time(null)); // Create this structure (top-level function "table of contents") static PyMethodDef testmod_functions[] = "buildtuple", testmod_buildtuple, METH_VARARGS, "Builds a tuple"}, NULL, NULL, 0, NULL} // Sentinel }; // Modify the testmod_defintion structure static struct PyModuleDef testmod_definition = PyModuleDef_HEAD_INIT, "testmod", "My super-awesome first python extension -1, testmod_functions };

14 PART II: PYTHON/C "CLASSES"

15 PYTHON OOP BASICS (REVIEW) # We're going to do this in C on later slides (and the labs). # Just for comparison here. class Foo(object): """ Class-level docstring """ def init (self, name): self.mname = name self.mval = 0 self.mlist = [] def str (self): return '["' + self.mname + " : " + str(self.mval) + "]" def bar(self): self.mval += 1 self.mlist.append(chr(random.randint(97,122))) return self.mval x = Foo("Bob") print(x.bar()) # 1 print(x) # "Bob" : 1 : ["q"]}

16 ADDING A CLASS (GOAL) # (Add this to our existing test code) x = testmod.testclass("bob") y = testmod.testclass("sue") print(x, y) # ["Bob" : 0], ["Sue" : 0] print(x.bar()) # 1 print(x, y) # ["Bob" : 1], ["Sue" : 0] for i in range(10): y.bar() print(x, y) # ["Bob" : 1], ["Sue" : 10]

17 OVERVIEW Create 4 additional structures: 1. [testclass] A C struct defining the C side of that "object" Can contain one or more basic types (floats, ints, etc.) Can contain PyObject's (e.g. for Python strings, lists, etc.) 2. [testclass_methods] An array of PyMethodDefs structures: one element for each non-special method in the class. 3. [testclasstype] A PyTypeObject: The definition of the new type (in Python). Includes "slots" for all the special functions (e.g. init, add, etc) 4. [testclass_members] An array of PyMemeberDef structures: one for each attribute of the class. The rest will be defining the C implementation of all methods. Most will have the signature PyObject* func(pyobject * self, PyObject * args)

18 1. THE C STRUCT AND 2. MEMBER-DEF typedef struct PyObject_HEAD PyObject * mname; int mvalue; } testclass; static PyMemberDef testclass_members[] = "mname", T_OBJECT_EX, offsetof(testclass, mname), 0, "the name of the thingy"}, "mvalue", T_INT, offsetof(testclass, mvalue), 0, "the value of the thingy"}, NULL} // Sentinel };

19 3. THE PYTYPEOBJECT A big one! Contains slots for all "special" methods (C function pointers) flags, pointers to structures (e.g. our member and method structs) NOTE: Make sure you include <structmember.h> static PyTypeObject testclasstype = PyVarObject_HEAD_INIT(NULL, 0) "testmod.testclass", /* tp_name */ sizeof(testclass), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */

20 3. THE PYTYPEOBJECT, CONT. 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT Py_TPFLAGS_BASETYPE, /* tp_flags */ "This is the testclass class (within the testmod module)", /* tp_doc. */ 0, /* tp_traverse */ 0, /* tp_clear */

21 3. THE PYTYPEOBJECT, CONT. }; 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ testclass_methods, /* tp_methods */ testclass_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */

22 MODIFICATIONS TO PYINIT_TESTMOD if (PyType_Ready(&testClassType) < 0) return NULL; // Create our module PyObject * mod = PyModule_Create(&testMod_definition); if (mod == NULL) return NULL; Py_INCREF(&testClassType); PyModule_AddObject(mod, "testclass", (PyObject*)&testClassType);

23 3A. DEFINE TP_NEW AND TP_DEALLOC static PyObject * testclass_new(pytypeobject * type, PyObject * args, PyObject * kwargs) testclass * obj = (testclass*)type->tp_alloc(type, 0); if (obj!= NULL) // Initialize mname to an empty string obj->mname = PyUnicode_FromString(""); if (obj->mname == NULL) Py_DECREF(obj); return NULL; } obj->mvalue = 0; } } return (PyObject*)obj; // Insert a pointer to the above function in the tp_new "slot" in testclasstype // This effectively re-defines the " new " method in python static void testclass_dealloc(testclass * obj) Py_XDECREF(obj->mName); Py_TYPE(obj)->tp_free((PyObject*)obj); } // Insert a pointer to the above function in the tp_dealloc "slot" in testclasstype // You'll need to cast the function pointer as a destructor

24 3A. DEFINE TP_INIT static int testclass_init(testclass * self, PyObject * args, PyObject * kwargs) if (!PyTuple_Check(args) PyTuple_Size(args)!= 1!PyUnicode_Check(PyTuple_GetItem(args, 0))) PyErr_SetString(PyExc_TypeError, "You must pass a single string to this method"); return -1; // Error } PyObject * temp_str = PyTuple_GetItem(args, 0); PyObject * old_str = self->mname; Py_INCREF(temp_str); self->mname = temp_str; Py_XDECREF(old_str); self->mvalue = 0; } return 0; // Success // Insert a pointer to the above function in the tp_init "slot" in testclasstype // (You'll need to cast it as a initproc function pointer // This effectively re-defines the " init " method in python

25 4. DEFINE TESTCLASS_METHODS AND FOO (A NON-SPECIAL METHOD) static PyObject * testclass_bar(pyobject * self, PyObject * args) testclass * obj = (testclass*)self; obj->mvalue++; return PyLong_FromLong(obj->mValue); } static PyMethodDef testclass_methods[] = "foo", (PyCFunction)testClass_bar, METH_VARARGS, "Increments mvalue and returns it"}, NULL}// Sentinel };

26 QUESTIONS?

C - extensions. only a small part of application benefits from compiled code

C - extensions. only a small part of application benefits from compiled code C - EXTENSIONS C - extensions Some times there are time critical parts of code which would benefit from compiled language 90/10 rule: 90 % of time is spent in 10 % of code only a small part of application

More information

Embedding Python in Your C Programs

Embedding Python in Your C Programs 1 of 7 6/18/2006 9:05 PM Embedding Python in Your C Programs William Nagel Abstract C, meet Python. Python, this is C. With surprisingly little effort, the Python interpreter can be integrated into your

More information

PYTHON IS SLOW. Make it faster with C. Ben Shaw

PYTHON IS SLOW. Make it faster with C. Ben Shaw PYTHON IS SLOW Make it faster with C Ben Shaw It s OK that Python isn t fast, you can write your slow functions in C! Everyone TABLE OF CONTENTS C Module vs C Types TABLE OF CONTENTS C Module vs C Types

More information

Išplė&mas. Esamo funkcionalumo papildymas naujomis galimybėmis

Išplė&mas. Esamo funkcionalumo papildymas naujomis galimybėmis Išplė&mas Esamo funkcionalumo papildymas naujomis galimybėmis Kam to reikia? Realizuoti naujus įtaisytuosius (built- in) objektų tipus Iškviesti C bibliotekų funkcijas ir sisteminius kvietimus Ko reikia?

More information

Python Optimization and Integration

Python Optimization and Integration [Software Development] Python Optimization and Integration Davide Balzarotti Eurecom Sophia Antipolis, France 1 When Python is not Enough Python is great for rapid application development Many famous examples...

More information

A study on scripting language APIs

A study on scripting language APIs A study on scripting language APIs Hisham H. Muhammad Advisor: Roberto Ierusalimschy Pontifícia Universidade Católica do Rio de Janeiro Centro Técnico Cientíco Departamento de Informática November 9, 2006

More information

Extending and Embedding Python

Extending and Embedding Python Extending and Embedding Python Release 3.4.3 Guido van Rossum and the Python development team February 25, 2015 Python Software Foundation Email: docs@python.org CONTENTS 1 Recommended third party tools

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled Interpreted vs Compiled Python 1 Java Interpreted Easy to run and test Quicker prototyping Program runs slower Compiled Execution time faster Virtual Machine compiled code portable Java Compile > javac

More information

redis-lua Documentation

redis-lua Documentation redis-lua Documentation Release 2.0.8 Julien Kauffmann October 12, 2016 Contents 1 Quick start 3 1.1 Step-by-step analysis........................................... 3 2 What s the magic at play here?

More information

Armin how Python was shaped by leaky internals

Armin how Python was shaped by leaky internals Armin Ronacher @mitsuhiko how Python was shaped by leaky internals Armin Ronacher @mitsuhiko Flask / Sentry / Lektor http://lucumr.pocoo.org/ The Leaky Interpreter Python is an insanely complex language

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

Extensions in C and Fortran

Extensions in C and Fortran Extensions in C and Fortran Why? C and Fortran are compiled languages Source code is translated to machine instructons by the compiler before you run. Ex: gfortran -o mycode mycode.f90 gcc -o mycode mycode.c

More information

Python Object Sharing. Steen Viken Valvåg

Python Object Sharing. Steen Viken Valvåg Python Object Sharing Steen Viken Valvåg December 2002 Abstract Language support for threads was introduced at a late stage in the Python development process. To accomodate that the majority of Python

More information

Assumptions. History

Assumptions. History Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand

More information

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules Lecture 3 Functions & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should

More information

Libgdb. Version 0.3 Oct Thomas Lord

Libgdb. Version 0.3 Oct Thomas Lord Libgdb Version 0.3 Oct 1993 Thomas Lord Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

http://tinyurl.com/cq-advanced-python-20151029 1 2 ##: ********** ## csuser## @[S## ********** guillimin.hpc.mcgill.ca class## ********** qsub interactive.pbs 3 cp -a /software/workshop/cq-formation-advanced-python

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Arrays, Pointers and Memory Management

Arrays, Pointers and Memory Management Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014 Answer to the question from last week strct->field Returns the value of field in the structure pointed to by

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science CSC148 Intro. to Computer Science Lecture 3: designing classes, special methods, composition, inheritance, Stack, Sack Amir H. Chinaei, Summer 2016 Office Hours: R 10-12 BA4222 ahchinaei@cs.toronto.edu

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Lecture Topics. Administrivia

Lecture Topics. Administrivia ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality

More information

ctypes extending python was never easier! Anant Narayanan Malaviya National Institute of Technology

ctypes extending python was never easier! Anant Narayanan Malaviya National Institute of Technology C! ctypes extending python was never easier! Anant Narayanan Malaviya National Institute of Technology So what is python? Dynamically typed, interpreted language Allows for fast prototyping, thanks to

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1 OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13]

More information

LECTURE 2. Python Basics

LECTURE 2. Python Basics LECTURE 2 Python Basics MODULES ''' Module fib.py ''' from future import print_function def even_fib(n): total = 0 f1, f2 = 1, 2 while f1 < n: if f1 % 2 == 0: total = total + f1 f1, f2 = f2, f1 + f2 return

More information

CS24 Week 2 Lecture 1

CS24 Week 2 Lecture 1 CS24 Week 2 Lecture 1 Kyle Dewey Overview C Review Void pointers Allocation structs void* (Void Pointers) void* Like any other pointer, it refers to some memory address However, it has no associated type,

More information

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules Lecture 3 Functions & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should

More information

Alien GOO a Lightweight C Embedding Facility. Jonathan Bachrach MIT CSAIL. Alien MIT 1 19DEC03

Alien GOO a Lightweight C Embedding Facility. Jonathan Bachrach MIT CSAIL. Alien MIT 1 19DEC03 Alien GOO a Lightweight C Embedding Facility Jonathan Bachrach MIT CSAIL Alien GOO @ MIT 1 Quick Goo Intro! Dynamic type-based object-oriented language! Interpreter semantics! Classes, multiple inheritance,

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13

Binghamton University. CS-120 Summer Introduction to C. Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Introduction to C Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13 Problem: Too Many Details For example: Lab 7 Bubble Sort Needed to keep track of too many details! Outer Loop When do

More information

CS 112: Intro to Comp Prog

CS 112: Intro to Comp Prog CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment:

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms

More information

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6 CMSC 313 Introduction to Computer Systems Lecture 8 Pointers, cont. Alan Sussman als@cs.umd.edu Administrivia Project 2 posted, due October 6 public tests s posted Quiz on Wed. in discussion up to pointers

More information

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python http://www.cs.cornell.edu/courses/cs1110/2019sp Lecture 3: Functions & Modules (Sections 3.1-3.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner,

More information

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

PyD Documentation. Release 1.0. Kirk McDonald

PyD Documentation. Release 1.0. Kirk McDonald PyD Documentation Release 1.0 Kirk McDonald Dec 27, 2017 Contents 1 Extending Python with D 3 1.1 Basics................................................... 3 2 Embedding Python in D 5 2.1 InterpContext...............................................

More information

CPSC 217 L01 Midterm

CPSC 217 L01 Midterm CPSC 217 L01 Midterm Duration: 50 minutes 4 March 2010 This exam has 55 questions and 10 pages. This exam is closed book. No notes, books, calculators or electronic devices, or other assistance may be

More information

The NumPy Array: A Structure for Efficient Numerical Computation

The NumPy Array: A Structure for Efficient Numerical Computation The NumPy Array: A Structure for Efficient Numerical Computation Presented at the G-Node Autumn School on Advanced Scientific Programming in Python, held in Kiel, Germany Stéfan van der Walt UC Berkeley

More information

Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017

Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017 Hw 1, Part 2 (Lab): Functioning smoothly! Using built-in functions Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017 First, try out some of Python's many built-in functions. These

More information

CS61C Midterm Review on C & Memory Management

CS61C Midterm Review on C & Memory Management CS61C Midterm Review on C & Memory Management Fall 2006 Aaron Staley Some material taken from slides by: Michael Le Navtej Sadhal Overview C Array and Pointer Goodness! Memory Management The Three Three

More information

HW1 due Monday by 9:30am Assignment online, submission details to come

HW1 due Monday by 9:30am Assignment online, submission details to come inst.eecs.berkeley.edu/~cs61c CS61CL : Machine Structures Lecture #2 - C Pointers and Arrays Administrivia Buggy Start Lab schedule, lab machines, HW0 due tomorrow in lab 2009-06-24 HW1 due Monday by 9:30am

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Extending and Embedding the Python Interpreter

Extending and Embedding the Python Interpreter Extending and Embedding the Python Interpreter Release 2.1.1 Guido van Rossum Fred L. Drake, Jr., editor July 20, 2001 PythonLabs E-mail: python-docs@python.org Copyright c 2001 Python Software Foundation.

More information

Extending and Embedding Python

Extending and Embedding Python Extending and Embedding Python Release 2.7.6 Guido van Rossum Fred L. Drake, Jr., editor November 10, 2013 Python Software Foundation Email: docs@python.org CONTENTS 1 Extending Python with C or C++ 3

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Python Short Course Lecture 5: Extending Python. Richard P. Muller Materials and Process Simulation Center Spring, 2000

Python Short Course Lecture 5: Extending Python. Richard P. Muller Materials and Process Simulation Center Spring, 2000 Python Short Course Lecture 5: Extending Python Richard P. Muller Materials and Process Simulation Center Spring, 2000 Extending Python Python is great for rapid application development Little overhead

More information

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003

Outline. Object Oriented Programming. Course goals. Staff. Course resources. Assignments. Course organization Introduction Java overview Autumn 2003 Outline Object Oriented Programming Autumn 2003 2 Course goals Software design vs hacking Abstractions vs language (syntax) Java used to illustrate concepts NOT a course about Java Prerequisites knowledge

More information

CSE 8B Intro to CS: Java

CSE 8B Intro to CS: Java CSE 8B Intro to CS: Java Winter, 2006 January 10 (Day 1) Introduction Unit Testing Administrative Details Programming assignments (30%) Weekly Due Monday night (midnight) Lowest assignment dropped Quizzes

More information

Extending and Embedding the Python Interpreter

Extending and Embedding the Python Interpreter Extending and Embedding the Python Interpreter Release 2.5.2 Guido van Rossum Fred L. Drake, Jr., editor 21st February, 2008 Python Software Foundation Email: docs@python.org Copyright c 2001-2008 Python

More information

ENGR (Socolofsky) Week 02 Python scripts

ENGR (Socolofsky) Week 02 Python scripts ENGR 102-213 (Socolofsky) Week 02 Python scripts Listing for script.py 1 # data_types.py 2 # 3 # Lecture examples of using various Python data types and string formatting 4 # 5 # ENGR 102-213 6 # Scott

More information

Advanced and Parallel Python

Advanced and Parallel Python Advanced and Parallel Python December 1st, 2016 http://tinyurl.com/cq-advanced-python-20161201 By: Bart Oldeman and Pier-Luc St-Onge 1 Financial Partners 2 Setup for the workshop 1. Get a user ID and password

More information

JTSK Programming in C II C-Lab II. Lecture 3 & 4

JTSK Programming in C II C-Lab II. Lecture 3 & 4 JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically

More information

Functions!!! Why functions? Functions provide good way to design systems!

Functions!!! Why functions? Functions provide good way to design systems! Functions!!! Why functions? Functions provide good way to design systems! Coding Design! DRY principle - Don't Repeat Yourself! Loops help with this! Functions/procedures/modules help even more! Modular

More information

Python Implementation Strategies. Jeremy Hylton Python / Google

Python Implementation Strategies. Jeremy Hylton Python / Google Python Implementation Strategies Jeremy Hylton Python / Google Python language basics High-level language Untyped but safe First-class functions, classes, objects, &c. Garbage collected Simple module system

More information

For Loops (Project 8)

For Loops (Project 8) For Loops (Project 8) Goals In this tutorial you will: Use a for loop to repeat an action a set number of times Find the position of the other satellite Program your satellite to move toward the other

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading

More information

Background. Reflection. The Class Class. How Objects Work

Background. Reflection. The Class Class. How Objects Work Background Reflection Turing's great insight: programs are just another kind of data Source code is text Manipulate it line by line, or by parsing expressions Compiled programs are data, too Integers and

More information

DevKitchen 2018 Python in Cinema 4D R20

DevKitchen 2018 Python in Cinema 4D R20 Python in Cinema 4D R20 Disclaimer text if necessary. Python in R20 Changes New Console c4dpy MAXON API 2 Python in R20 Changes Python API not affected by C++ API backward compatibility break See Python

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28)   First Name: Last Name: NetID: CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) http://www.cs.cornell.edu/courses/cs1110/2016sp/labs/lab01/lab01.pdf First Name: Last Name: NetID: Goals. Learning a computer language is a lot like learning

More information

Welcome to CSC148! Introduction to Computer Science

Welcome to CSC148! Introduction to Computer Science Welcome to CSC148! Introduction to Computer Science Amir H. Chinaei, Summer 2016 ahchinaei@cs.toronto.edu http://www.cs.toronto.edu/~ahchinaei/ Office hours: R 10 BA4222 Today Course Outline (bird s-eye

More information

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015

Lecture 22: Java. Overall Structure. Classes & Objects. Every statement must end with ';' Carl Kingsford, , Fall 2015 Carl Kingsford, 0-0, Fall 0 Lecture : Java Overall Structure Classes & Objects Every function in Java must be inside a class, which are similar to Go's struct s. For example: 8 9 0 8 9 class MyProgram

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

More information

Functions in C C Programming and Software Tools

Functions in C C Programming and Software Tools Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

The Python/C API Release Guido van Rossum and the Python development team

The Python/C API Release Guido van Rossum and the Python development team The Python/C API Release 3.4.3 Guido van Rossum and the Python development team February 25, 2015 Python Software Foundation Email: docs@python.org CONTENTS 1 Introduction 3 1.1 Include Files.............................................

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

Python Programming Exercises 1

Python Programming Exercises 1 Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them

More information

Jython. secondary. memory

Jython. secondary. memory 2 Jython secondary memory Jython processor Jython (main) memory 3 Jython secondary memory Jython processor foo: if Jython a

More information

6.092: Java for 6.170

6.092: Java for 6.170 6.092: Java for 6.170 Lucy Mendel MIT EECS MIT 6.092 IAP 2006 1 Course Staff Lucy Mendel Corey McCaffrey Rob Toscano Justin Mazzola Paluska Scott Osler Ray He Ask us for help! MIT 6.092 IAP 2006 2 Class

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Intro to Computer Science II

Intro to Computer Science II Intro to Computer Science II CS112-2012S-09 More Arrays and Static David Galles Department of Computer Science University of San Francisco 09-0: Array Review Arrays store a list of objects or primative

More information

Not-So-Mini-Lecture 6. Modules & Scripts

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

UCT Department of Computer Science Computer Science 1017F. Functions. Lighton Phiri April 2015

UCT Department of Computer Science Computer Science 1017F. Functions. Lighton Phiri April 2015 UCT Department of Computer Science Computer Science 1017F Functions Lighton Phiri April 2015 Functions in pespective Function definition Function signature Function invocation Input

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Contents. Chapter 1 Overview of the JavaScript C Engine...1. Chapter 2 JavaScript API Reference...23

Contents. Chapter 1 Overview of the JavaScript C Engine...1. Chapter 2 JavaScript API Reference...23 Contents Chapter 1 Overview of the JavaScript C Engine...1 Supported Versions of JavaScript...1 How Do You Use the Engine?...2 How Does the Engine Relate to Applications?...2 Building the Engine...6 What

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 03: Data Types and Console Input / Output Introduction to Types As we have already seen, 1 computers store numbers in a binary sequence of bits. The organization

More information

CSE 431S Type Checking. Washington University Spring 2013

CSE 431S Type Checking. Washington University Spring 2013 CSE 431S Type Checking Washington University Spring 2013 Type Checking When are types checked? Statically at compile time Compiler does type checking during compilation Ideally eliminate runtime checks

More information

Lecture 3: Functions & Modules

Lecture 3: Functions & Modules http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 3: Functions & Modules (Sections 3.1-3.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner,

More information

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018 CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Outline. More optimizations for our interpreter. Types for objects

Outline. More optimizations for our interpreter. Types for objects Outline More optimizations for our interpreter Types for objects Optimization Eliminate tree walks: object creation, method calls fish initialize get_ grow eat colorfish color set_color get_color pickyfish

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

Advanced Systems Programming

Advanced Systems Programming Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short

More information

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce Lecture 38: Python CS 51G Spring 2018 Kim Bruce Announcements Test program 2 Academic Honesty Guidelines! Quiz Friday (Strings & Streams) Lecture Friday will be in lab Write searches and sorts in Python

More information

Integer Representation

Integer Representation Integer Representation Representation of integers: unsigned and signed Modular arithmetic and overflow Sign extension Shifting and arithmetic Multiplication Casting 1 Fixed- width integer encodings Unsigned

More information

Data Storage. August 9, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 August 9, / 19

Data Storage. August 9, Indiana University. Geoffrey Brown, Bryce Himebaugh 2015 August 9, / 19 Data Storage Geoffrey Brown Bryce Himebaugh Indiana University August 9, 2016 Geoffrey Brown, Bryce Himebaugh 2015 August 9, 2016 1 / 19 Outline Bits, Bytes, Words Word Size Byte Addressable Memory Byte

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College August 29, 2018 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15 1 LECTURE 1: INTRO Introduction to Scientific Python, CME 193 Jan. 9, 2014 web.stanford.edu/~ermartin/teaching/cme193-winter15 Eileen Martin Some slides are from Sven Schmit s Fall 14 slides 2 Course Details

More information

CSC148: Week 1

CSC148: Week 1 CSC148: Week 1 http://www.cdf.utoronto.ca/~csc148h/summer/ Sophia Huynh Summer 2018 1 Outline Introduction Object-Oriented Design 2 Your instructor Sophia Huynh Master's Student Undergrad was done at UofT

More information