background preloader

The History of Python

The History of Python

Откуда идут «функциональные» корни Python / Python Я никогда не полагал, что Python попадет под влияние функциональных языков, независимо от того что люди говорят или думают. Я знаком с императивными языками, такими как C и Algol68 и хотя я сделал функции объектами «первого класса», я не рассматривал Python как язык функционального программирования. Однако, было ясно, что пользователи хотят больше от списков и функций. Операции над списками применялись к каждому элементу списка и создавали новый список. Например: def square(x): return x*x vals = [1, 2, 3, 4] newvals = [] for v in vals: newvals.append(square(v)) На функциональных языках, таких как Lisp и Scheme, операции, такие как эта были разработаны как встроенные функции языка. def map(f, s): result = [] for x in s: result.append(f(x)) return result def square(x): return x*x vals = [1, 2, 3, 4] newvals = map(square,vals) Тонкость вышеупомянутого кода в том, что многим людям не нравился факт, что функция применяется к элементам списка как набор отдельных функций.

BeginnersGuide New to programming? Python is free and easy to learn if you know where to start! This guide will help you to get started quickly. Chinese Translation/中文版入门 New to Python? Read BeginnersGuide/Overview for a short explanation of what Python is. Getting Python Next, install the Python 3 interpreter on your computer. There are also Python interpreter and IDE bundles available, such as Thonny. At some stage, you'll want to edit and save your program code. Learning Python Next, read a tutorial and try some simple experiments with your new Python interpreter. If you have never programmed before, see BeginnersGuide/NonProgrammers for a list of suitable tutorials. Most tutorials assume that you know how to run a program on your computer. Some sites offer in-browser coding for those who want to learn Python: Print a cheat sheet of the most important Python features and post it to your office wall until you know the basics well. Need Help? Need help with any of this? Complete list of Beginner's Guide pages

Probably Overthinking It: Regression with Python, pandas and StatsModels I was at Boston Data-Con 2014 this morning, which was a great event. The organizer, John Verostek, seems to have created this three-day event single-handedly, so I am hugely impressed. Imran Malek started the day with a very nice iPython tutorial. The description is here, and his slides are here. And Imran very kindly let me use his laptop to project slides for my talk, which was next. Regression is a powerful tool for fitting data and making predictions. As an example, I will use data from the National Survey of Family Growth to generate predictions for the date of birth, weight, and sex of an expected baby. This talk is appropriate for people with no prior experience with regression. And here are my slides: The material for this talk is from the second edition of Think Stats, which is in production now and scheduled for release in early November. As I expected, I prepared way more material than I could present. I believe video of the talk will be available soon.

Twisted Twisted is an event-driven networking engine written in Python and licensed under the open source ​MIT license. Twisted runs on Python 2 and an ever growing subset also works with Python 3. Twisted makes it easy to implement custom network applications. Here's a TCP server that echoes back everything that's written to it: from twisted.internet import protocol, reactor, endpoints class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class EchoFactory(protocol.Factory): def buildProtocol(self, addr): return Echo() endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory()) reactor.run() Learn more about ​writing servers, ​writing clients and the ​core networking libraries , including support for SSL, UDP, scheduled events, unit testing infrastructure, and much more. Twisted includes an event-driven web server. Learn more about ​web application development, ​templates and Twisted's ​HTTP client. Twisted includes a sophisticated IMAP4 client library.

PEP 8 -- Style Guide for Python Code Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such).For example, do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b. This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.Comparisons to singletons like None should always be done with is or is not, never the equality operators.Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

The Python I Would Like To See This post is surprisingly confused, it is phrased as a complaint about the language, then immediately degrades into CPython implementation specifics that have little bearing on the usability of the language itself. Ronacher should also know better than to post microbenchmarks like the one provided here, especially without corresponding (C) profiler output. At the C level, slots allow the implementation constant-time access to the most common code paths for an object, and especially when you have C code calling other C code via the type system (IMHO the primary use for Python, and still its strongest use case), "interpreter overhead" is reduced to a few extra memory indirection operations. In the alternative world, sure, perhaps some microbenchmark may behave faster, but now systemically, and for e.g. "reduce(operator.add, range(1000))" requires more hash table lookups than I can count.

Устранение Хвостовой рекурсии / Python Я недавно написал в своем блоге Python History пост «The origins of Python's functional features» (перевод). Упоминание о том, что Python не поддерживает хвостовую рекурсию (TRE) сразу спровоцировало несколько комментариев о том, как жаль, что Python не поддерживает данную оптимизацию. Появились ссылки на недавние записи в других блогах о том, что TRE может быть добавлена в Python легко. Вот длинный ответ.Во-первых, как кто-то заметил в комментариях, TRE является несовместимой с нормальной трассировкой стека: когда устранена хвостовая рекурсия, нет никакого стекового фрейма, оставленного, чтобы вывести traceback, если что-то пойдет не так. Во-вторых, идея, что TRE — просто оптимизация, которую отдельная реализация Python может реализовывать или нет, является неправильной. В-третьих, я не верю в рекурсию как базис всего программирования. Наконец, давайте посмотрим на то, как мы могли бы реализовать устранение хвостовой рекурсии. def f(x): if x > 0: return f(x-1) return 0

The Hitchhikers Guide to Python! — pythonguide 0.0.1 documentation Greetings, Earthling! Welcome to The Hitchhiker’s Guide to Python. This is a living, breathing guide. This handcrafted guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis. This guide is opinionated in a way that is almost, but not quite, entirely unlike Python’s official documentation. Note The use of Python 3 is highly preferred over Python 2. Let’s get started! Getting Started with Python New to Python? Properly Install Python on your system: Using Virtualenvs with Pipenv: Python Development Environments This part of the guide focus on the Python development environment, and the best-practice tools that are available for writing Python code. Writing Great Python Code This part of the guide focuses on the best-practices for writing Python code. Scenario Guide for Python Applications This part of the guide focuses on tool and module advice based on different scenarios. Additional Notes

The Python I Would Like To See written on Saturday, August 16, 2014 It's no secret that I'm not a fan of Python 3 or where the language is currently going. This has led to a bunch of emails flying my way over the last few months about questions about what exactly I would prefer Python would do. Python is definitely a language that is not perfect. I want to take you on a journey that starts with a small oddity in the interpreter (slots) and ends up with the biggest mistake in the language design. In general though these posts will be an exploration about design decisions in the interpreter and what consequences they have on both the interpreter and the resulting language. Language vs Implementation I added this particular paragraph after I wrote the initial version of this article because I think it has been largely missed that Python as a language and CPython as the interpreter are not nearly as separate as developers might believe. Slots By far my biggest problem with the language is the stupid slot system. Yes. $ .

Related: