貼一些 Python 的筆記

項目當中用到 https://github.com/Cirru/sepal.py
貼一點筆記.html

PyPI

社區模塊方案選用 pip, 在 PyPI 上查詢模塊, 入門教程:
http://peterdowns.com/posts/first-time-with-pypi.htmlnode

python setup.py register -r pypitest
python setup.py sdist upload -r pypitest
python setup.py register -r pypi
python setup.py sdist upload -r pypi

尾遞歸

Python 不支持尾遞歸優化, 社區有提供優化的腳本(不過實際項目使用有問題):
http://calebmadrigal.com/tail-call-optimization-in-python/python

刷新 REPL 引用模塊

一樣模仿 Clojure 能夠在 REPL 當中測試函數, 那麼刷新模塊像是這樣:git

import sys

if 'myModule' in sys.modules:  
    del sys.modules["myModule"]

http://stackoverflow.com/a/3194343/883571github

AST

AST 的文檔比較豐富的, 不過也比較龐雜, 實現起來估計也會累
考慮到要實現的 AST 的量, 我考慮暫停試驗算了.
http://eli.thegreenplace.net/2009/11/28/python-internals-working-with-python-asts/
https://pypi.python.org/pypi/astdump/3.3
http://greentreesnakes.readthedocs.org/en/latest/tofrom.html
https://docs.python.org/2/library/ast.htmlexpress

import ast
a = ast.literal_eval("[1,2,3,4]") //evaluate an expression safely.
import ast
source = '2 + 2'
node = ast.parse(source, mode='eval')
ast.dump(node)

http://stackoverflow.com/a/13350121/883571函數

還能夠用 codegen.to_source 生成代碼:post

import ast
import codegen

ast.parse('print(1 + 2)') # return AST
ast.dump(ast.parse('print(1 + 2)')) # return readable AST
codegen.to_source.dump(ast.parse('print(1 + 2)')) # generate code

AST 當中用到一些 keyword arguments:
http://stackoverflow.com/a/1419160/883571測試

import

Python 模塊引用一句 Module Search Path 查找, 能夠從 sys.path 查看
https://docs.python.org/2/tutorial/modules.html#the-module-search-path優化

package 的目錄會有 __init__.py 文件, 引入須要暴露的模塊
好比這樣是把 sepal.py 文件的 transform 函數暴露出去

from sepal import transform

讀取文件

with open ("data.txt", "r") as myfile:
    data=myfile.read().replace('\n', '')

http://stackoverflow.com/a/8369345/883571

Test

安裝 nosetests 來進行測試
http://pythontesting.net/framework/nose/nose-introduction/
http://pythontesting.net/framework/unittest/unittest-introduction/

Dependency

install_requires 字段用於聲明依賴
http://www.scotttorborg.com/python-packaging/dependencies.html

相關文章
相關標籤/搜索