Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old November 8th, 2012, 08:18 AM
Random Random is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 72 Random User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 47 m 23 sec
Reputation Power: 10
Web Framework

Hello,

I am trying to teach myself one of the simpler web framework namely Bottle or Flask. I have tried Django but found it to be really complicated. Flask / Bottle seems to me slightly smaller and easier to learn, but there is one barrier that I just can not overcome and it appears right in the beginning of the tutorial "decorators". I have looked at some explanations or examples and just can not get what they are or how to use them. The only think that I do understand is that you are passing a function to another function which can modify the original one.

Could someone please explain with simple example how to write and use one.

Thank you.

Reply With Quote
  #2  
Old November 8th, 2012, 10:39 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,358 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 37 m 48 sec
Reputation Power: 383
The j language has adverbs as a part of speech. Adverbs modify verbs. Decorators are a similar concept. Apparently I can still write a decorator, see below. If you actually test and examine the result from this code you'll see that the decorator runs when the module is imported.

We know that the decorator must return a callable, and that
Code:
@dec2
@dec1
def func(arg1, arg2, ...):
    pass

#is equivalent to:

def func(arg1, arg2, ...):
    pass
func = dec2(dec1(func))


Decorator examples, the first of which even I can understand.

Code:
# passes doctest
# $ python3 -m doctest -v NAME_OF_THIS_FILE.py

def offset(function):
    print('the offset function ran with argument %s'%str(function))
    def f(self,item):
        return function(self,item-self.QuadIO)
    return f

class LIST(list):
    '''
        list with offset index origin.
        >>> LIST('abc',1)[1]   ########<<<<=== HERE this is the purpose of the class
        'a'
    '''
    def __init__(self,iterable,index_origin=0):
        list.__init__(self,iterable)
        self.QuadIO = index_origin

    @offset
    def __getitem__(self,item):
        return list.__getitem__(self,item)

I can't describe this better than the various PEPs. Find the PEP index at python.org. Search for decorator. Read them til yer ill.
__________________
[code]Code tags[/code] are essential for python code!

Reply With Quote
  #3  
Old November 8th, 2012, 11:44 AM
Random Random is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 72 Random User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 47 m 23 sec
Reputation Power: 10
Thank you, I just guess there are some things that are so way above you that no matter how much you try you will not get.
So I guess that you can not learn a simple framework if you dont get that. I thought that flask and bottle are supposed to be simple ones??

You know there are a couple of things for which I could not find any easy to understand tutorials. I do have a basic understanding of classes but have not found any tut on what are so called magic methods or how to use them in simple terms. I dont mean simple one like __init__ but all others which are used everywhere.

Thank you once again regarding decorators, I guess its just not for me to get a grasp.

Reply With Quote
  #4  
Old November 8th, 2012, 12:42 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,358 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 37 m 48 sec
Reputation Power: 383
What is a magic method? Name a few. Name three, as my sixth grade social studies teacher demanded.

Here's another decorator example.
Code:
import pprint

def debug(function):
    name = str(function).split()[1]
    print('Enunciate function %s.'%name)
    def debugged(*args,**kwargs):
        print('{Calling %s(*%s,**%s)'%(
            name,pprint.pformat(args),pprint.pformat(kwargs)))
        result = function(*args,**kwargs)
        print('result %s}'%pprint.pformat(result))
        return result
    return debugged

@debug
def piglatin(word):
    try:
        if 2 < len(word):
            return word[1:]+word[0]+'ay'
    except:
        pass
    return word

def square(n):
    return n*n


print(piglatin('pig'))
print(piglatin(word='latin'))


print(square(16))


Now, even if you don't understand what the devil's going on you import this debug function into your name space, and you can get insight into functions you're having trouble with merely by writing @debug on the source line before your function definition. Without making any other changes in your program every time that function is called your output will include a message telling you the functions name, its arguments, and the output.
Code:
@debug
def confusing(many,arguments):
    #computations and logic
    return result or None


Firstly, you can use decorators without understanding how they work. Oh---be sure not to use the decorator that emails me your country personal identification number.

Secondly, you can understand decorators. Run the program. Make a tiny change. Run the program again. How did the output change? Don't understand pprint.pformat ? Look it up in the python library documents. Don't understand **kwargs? Hunt for passing a dictionary as the key word arguments in a function call.


Code:
$ python3 p.py
Enunciate function piglatin.
{Calling piglatin(*('pig',),**{})
result 'igpay'}
igpay
{Calling piglatin(*(),**{'word': 'latin'})
result 'atinlay'}
atinlay
256

I ran the program above. First it prints Enunciate... That comes from the execution of debug in the decorator. How do I know? I suppose a clever person would use pdb but I'm not, so I put print statements in the code and run it again:
Code:
#...
print('using my decorator')
@debug
def piglatin(word):
    try:
        if 2 < len(word):
            return word[1:]+word[0]+'ay'
    except:
        pass
    return word
print('decorated!')
#...


Don't understand how piglatin works? Try it alone. Use non-string arguments. Use short string arguments. (hahaha I didn't make any of these tests...)

Last edited by b49P23TIvg : November 8th, 2012 at 12:46 PM.

Reply With Quote
  #5  
Old November 8th, 2012, 01:16 PM
Random Random is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 72 Random User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 47 m 23 sec
Reputation Power: 10
Magic Methods as they are called __xxx__.

For example, i see quite frequently something like this: cls.__mro__ what is that?

Regarding magic methods its something like this:

Code:
>>> dir('hello')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__',


How do you use them, why, where

Thanks once again

Reply With Quote
  #6  
Old November 8th, 2012, 02:09 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,358 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 37 m 48 sec
Reputation Power: 383
Code:
'''
    $ python3 p.py
    invoke my_string.__add__
    hello world!

    invoke my_string.__len__
    5

    (<class '__main__.my_string'>, <class 'str'>, <class 'object'>)
'''

class my_string(str):

    def __len__(self):
        print('invoke my_string.__len__')
        return str.__len__(self)

    def __add__(self,other):
        print('invoke my_string.__add__')
        return my_string(str.__add__(self,other))


hi = my_string('hello')
print(hi + ' world!')
print('')
print(len(hi))
print('')
print(my_string.__mro__)
my_string('hello') calls a constructor to make this object. Which __init__ did it use? When looking for __init__ the method resolution order says: "first look in my_string, then look in str, finally look in object". my_string hasn't got an __init__; str has an __init__; python builds str.__init__ to construct the my_string object.

In hi + ' world!' the + operator tells python to hunt for an __add__ method. Using the __mro__ it finds a definition in class my_string and uses that definition. That method, as you can tell by looking at it, prints a message and then explicitly calls str.__add__ to finish the job. And then I decided that the result type should be my_string instead of str, and that's why I stuck the expression inside my_string(string_object).

What about len(hi)? len looks for an object's __len__ method. It finds one in my_string. I programmed it to behave corresponding to __add__ .

There are a whole lot of these, some of which changed name between python 2 and 3, some make iterators work, some are used to implement context (with statement), there's a yield statement, a next() functions, all the operators left and right.

Thankfully you can't also change operator precedence in these nasty languages (C++, python, and the like). a*b+c evaluates
(a.__mul__(b)).__add__(c)


j doesn't overload operators, the only data structure is array, and sentences of verbs and nouns evaluate from right to left. j is easier.

Reply With Quote
  #7  
Old November 8th, 2012, 03:56 PM
Random Random is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 72 Random User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 47 m 23 sec
Reputation Power: 10
hi,

I would like to say, that i am very grateful for the time you took to try to explain and answer my questions, but now I understand why I could not understand this subject matter it is way above my head.

lol I love python and feel that it is a great language and I felt that I could even attempt to look for an entry level job using python, but hey that feeling just passed.

Reply With Quote
  #8  
Old November 8th, 2012, 04:19 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,358 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 3 Days 9 h 37 m 48 sec
Reputation Power: 383
dude or dudette I can't find a python job either. Then again, internet/database/gui programming aren't my strengths.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Web Framework

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap