Saturday 2 September 2017

Python

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.
Whenever you use a for loop, or map, or a list comprehension, etc. in Python, the next method is called automatically to get each item from the iterator, thus going through the process of iteration.
 iterable is an object that you can get an iterator from.
>>> s = 'cat'      # s is an ITERABLE
                   # s is a str object that is immutable
                   # s has no state
                   # s has a __getitem__() method 

>>> t = iter(s)    # t is an ITERATOR
                   # t has state (it starts by pointing at the "c"
                   # t has a next() method and an __iter__() method

>>> next(t)        # the next() function returns the next value and advances the state
'c'
>>> next(t)        # the next() function returns the next value and advances
'a'
>>> next(t)        # the next() function returns the next value and advances 't' 
>>> next(t)        # next() raises StopIteration to signal that iteration is complete
 how python is interpreted.
- Python program runs directly from the source code.

- Each time Python programs are executed code is required.

- Python converts source code written by the programmer into intermediate language which is again translated into the native language / machine language that is executed. So Python is an Interpreted language.

- It is processed at runtime by the interpreter.

Global varaibles between files

# settings.py

def init():
    global myList
    myList = []
Next, your subfile can import globals:
# subfile.py

import settings

def stuff():
    settings.myList.append('hey')
Note that subfile does not call init() -- that task belongs to main.py:
# main.py

import settings
import subfile

settings.init()          # Call only once
subfile.stuff()         # Do stuff with global var
print settings.myList[0] # Check the result
This way, you achieve your objective while avoid initializing global variables more than once.

No comments:

Post a Comment