Wednesday, September 30, 2015

Yield Expression and Generator Function in Python

Yield expressions are only used within a generator function. Here is an example:

>>def pp():
     x = yield      #1
     yield x*x       #2
     yield x*x*x     #3
     yield x*x*x*x   #4 
     yield x*x*x*x*x   #5
     yield x*x*x*x*x*x   #6

>>g = pp()
>>next(g)     #starts the generator and executes line #1
>>g.send(5)  #sends value 5 to x at line #2 and gets the result
25
>>next(g)     #gets the result of next line #3
125
>>next(g)     #gets the result of next line #4
625
>>g.send(2)  #gets the result of next line #5 
3125       #cannot send a new value in the middle of execution
>>next(g)     #gets the result of next line #6
15625
>>next(g)    #Throws StopIteration exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Saturday, September 12, 2015

Vim AutoCompletion for Python

Installing Pydiction to enable Auto-Completion for Python in Vi (Vim) editor:
1. First install Pathogen using the System Package Manager.
2. Download vimogen int the home directory using command-line:
 git clone https://github.com/rkulla/vimogen.git
3. Create .vim and .bundle directories by command-line:
 mkdir ~/.vim
 mkdir ~/.vim/bundle
4. Create file .vimogen_repos with the following content:
 echo "https://github.com/rkulla/pydiction.git" > ~/.vimogen_repos
5. Run vimogen by command-line:
  ~/vimogen/vimogen.sh   (and type 1 to install) 
  This will install pydiction in directory ~/.vim/bundle/
5. Under ~.vim do the following link:
  cd ~/.vim
  ln -s bundle/pydiction/after .
6. edit ~/.vimrc file and add the following lines:
filetype plugin on
let g:pydiction_location = '~/.vim/bundle/pydiction/complete-dict'
if has("autocmd")
  autocmd FileType python set complete+=k/path/to/pydiction iskeyword+=.,(
endif " has("autocmd")

That all you need to do. 
Now open an existing or new *.py file and check auto-completion by typing any python keyword or module partially and press tab to show the available choices.
For further reading check the following links.
http://www.vim.org/scripts/script.php?script_id=850
http://rkulla.github.io/pydiction/