« first day (2037 days earlier)      last day (2916 days later) » 

1:51 AM
morning guys. :)
anybody here use tensorflow before?
 
2:03 AM
nope. Heard of it, but that's about it
 
2:29 AM
i see. I'm just wondering why does it say on the udacity course for deep learning with tensor flow that python experience of 2 years is recommended.
@WayneWerner do people need to have strong knowledge in python before learning ML/ DL.
 
That seems odd to me... I mean, unless it's doing some ultra-advanced stuff
like... metaprogramming or something
unless in the course they just totally ignore any kind of Python terms (e.g. list/generator comps)
and just expect you to know it
that being said, given like... numpy/scipy, a lot of times they have their own implementation of similar concepts (e.g. map/reduce), so I'm not sure that would really even matter then
 
i see. thanks for the tip. just wondered why it mentioned 2 years experience
 
I've never taken the course, of course
 
@btw was to ask your experience. what is the best way to learn python libraries quickly. does it first require strong knowledge in python. Is books like Python Cookbook (david Beazley) useful for beginner-intermediate programmers
 
How much Python experience do you have? (and programming in general?)
 
2:39 AM
couple months
 
for both?
 
i've learned most stuff up until metaprogramming and decorators.
yeah for both.
 
decorators aren't too hard to grasp - have you ever passed a function around before?
 
so functions, classes im fine
passed a function? you mean like JS passing in functions as arguments?
yeah i have some basics
 
e.g.
 
2:41 AM
often I find that python libraries end up having their own syntax. I end up studying the library itself, rather than relying on python knowlege.
is this correct?
 
def my_func(arg):
    print('You passed', arg)

def other_thing(func):
    print("I'm calling func now!")
    func(42)

other_thing(my_func)
 
ya. i have some experience with it from javascript
 
if you look at that code and know what it's doing, then you have a fundamental understanding of how decorators work
 
i see
 
You'd actually see a decorator used like...
 
2:45 AM
Night cabbage.
 
@WayneWerner you asking me you mean?
 
        def other_thing(func):

            def wrapper(arg):
                print("I'm calling func now, cause I needed to do a fancy thing!")
                return func(42)
            return wrapper

        @other_thing
        def my_func(arg):
            print('You passed', arg)


        my_func(13)
I think that's valid anyway, heh.
They're pretty much just used when there's some sort of common behavior that you want to apply to the functions that are called
 
@WayneWerner i see. yeah. always got confused by this.
 
I definitely was, too, when I started.
Let's start with this example...
value = 42
def set_value():
    global value
    value = 12
set_value()
simple, and pretty contrived
but an example, nonetheless
you grok what's happening there, right?
 
yeah
nothing happened
well its not printing anything
 
2:53 AM
yeah, if you were to print value you'd see it's got 12
 
yeah
well. it makes sense. due to global?
 
right
so, let's say we want to ensure that only managers can set the value
value = 42
role = 'ADMIN'

def set_value():
    global value
    if role == 'ADMIN':
        value = 12
    else:
        print('You are not authorized')

set_value()
print(value)
so if you change the role, you'll see what happens
so far so good?
 
ah yea.
role takes on global value role
but if i declare it within function, then take on new value?
 
well, technically Python just looks for it in an outer scope (LEGB I think is the order? Local, Enclosing, Global, Builtin?)
it doesn't find the name locally, and the enclosing scope is the global namespace, so it finds role there and uses that value
 
ah. it only works at function level right. not block scope level?
 
2:58 AM
e.g.?
 
im comparing it to javascript
apparently can declare a function within an if statement eg
so within a function there are multiple scopes
 
oh, yeah, you can declare a function within a function
 
ah i see. but actually im confused how does it related to decorators.
and metaprogramming
 
value = 'global'
def enclosing():
    value = 'enclosing'
    print('enclosing value is: ', value)
    def function():
        print(value)
        print('function value is: ', value)
enclosing()
print('global value is: ', value)
we're getting there... the scoping part isn't the bit to focus on here
just that we're using some value from outside the function to decide how the function behaves
so if you were the function
role is not your responsibility
you don't care where it comes from or how it's set
just that when you ask for the role, you don't get a NameError.
 
how to call function value is:
is it like this
value = 'global'
def enclosing():
value = 'enclosing'
print('enclosing value is: ', value)
def function():
print(value)
print('function value is: ', value)
return function()
 
3:04 AM
continuing our example, we want to have more than just setting a value - we also want to be able to update a widget:
value = 42
role = 'ADMIN'

def set_value():
    global value
    if role == 'ADMIN':
        value = 12
    else:
        print('You are not authorized')


def update_widget(setting):
    global widget
    if role == 'ADMIN':
        widget = setting
    else:
        print('You are not authorized')
set_value()
update_widget('4 million volts')
print(value)
print(widget)
@Ming if you edit the message and click the 'fixed font' button ---> then it will fix the formatting ;)
 
yup. i forgot
value = 'global'
def enclosing():
    value = 'enclosing'
    print('enclosing value is: ', value)
    def function():
        print(value)
        print('function value is: ', value)
    return function()
i couldnt call the inner function within enclosing()
is that correct way to invoke it?. it gives me the inner value.
 
oh, right, yeah.
forgot to actally call that in the example -_-
 
ah ok
 
@WayneWerner so in our new example...
 
yeah. i get your latest example.
 
3:07 AM
you'll notice somthing that should stick out to you - especially if you've heard of DRY
i.e. Don't Repeat Yourself
 
yeah. heard about it.
 
you can see that we've got this same code dealing with checking the role, written twice
 
one thing im confused.
against with Javascript.
value = 42
role = 'ADMIN'

def set_value():
    # global value
    if role == 'ADMIN':
        value = 12
    else:
        print('You are not authorized')
 
(sure, not a big deal, considering it's just one line. But maybe it's more complicated than that in a real-world situation.)
 
is the value 12
it still is 42
 
3:09 AM
still 42
 
i thought value is changed. if i comment out global value in function
oh , so inner functions cannot modify global values
?
 
value is set in the local scope, i.e. the function
 
ah i see.
ok yes
 
well... they can modify global values
they just can't re-bind the global names
 
you need the global word?
to modify correct?
 
3:10 AM
e.g.
values = [1,2,3]
def add_value():
    values.append(42)
add_value()
print(values)
you're modifying values, a non-local
but you're not changing the name
have you done any C/++ programming, or just JS?
 
i have done only js and python
def set_value():
    print(value) # <<<<<< Error
    if role == 'ADMIN':
        value = 12
    else:
        print('You are not authorized')
    print(value, '------')
meaning that within local scope. it does not allow to call global scope?
 
correct. That's because locally the name does not exist yet
if you change value = 12 to not_the_value = 12 (or pass), then that code will work
because you cannot use a name before it's bound
 
but i thought legb
 
⚘ python
Python 3.5.1 (default, Mar  3 2016, 09:29:07)
[GCC 5.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = 42
 
it will look for global scope if not found in local
 
3:14 AM
exactly. So python looks in the local scope and says, "ah, I see that there is a value being bound here. It's not been bound yet, so I can't use it, oh noes!"
it does find it locally, just not bound to a value yet
 
i see. so basically it does not take into account that value is declared in global
 
in js it accidentally creates a global variable
 
in js this will work right. because if not bound in local, it will assume global binding
 
and even if it doesn't exist in the global binding, js will just create it there.
 
i see. got it.
 
3:16 AM
so... back to decorators and their utility
so we've got this functionality of checking for admin-ish rights
 
yeap
 
now, we could factor out the check into a function, like this...
def user_has_valid_role(*roles):
    if role not in roles:
        print('Role {!r} not in required roles {!r}'.format(role, roles))
        return False
    else:
        return True


def set_value():
    global value
    if user_has_valid_role('ADMIN'):
        value = 12
    else:
        print('You are not authorized')


def update_widget(setting):
    global widget
    if user_has_valid_role('ADMIN', 'MANAGER'):
        widget = setting
    else:
        print('You are not authorized')
so, hooray, that works. But our functions still have a little extra noise in them - namely, they're still checking the authorization.
That's not necessarily part of setting the value or updating the widget
but we've got that logic in there still the same.
wouldn't it be nice if we could somehow still require the permissions, without having that code inside our functions?
That's where decorators come into play
 
so you mean without having to call user_has_valid_role inside the functions
decorator will solve that?
 
yeah, so we could just put:

    def set_value():
        global value
        value = 12
that's nice and clean
 
@user_has_valid_role
def set_value1():
	global value
	value = 12

def update_widget(setting):
    global widget
    if user_has_valid_role('ADMIN', 'MANAGER'):
        widget = setting
        print(widget)
    else:
    	print('You are not authorized to update the widget')

# set_value()
set_value1()
update_widget('4 million volts')
print(value)
print(widget)
like this?
i got error
bool object is not callable
 
3:26 AM
yeah, so we need to change up our code a bit
    as a first step, try this:

    def requires_role(func):
        print('Func is ', func)

    @requires_role
    def set_value():
        global value
        value = 12
You'll notice that if you just run that, it prints
Func is <function set_value at 0x7f92d9fb1ae8> for example
 
yeah. i
also get error
nonetype object is not callable
after than
at set_value()
 
if you call set_value()
add return 42 in requires_role
what does that tell you?
 
seems to me that decorator function is passing value to set_value()?
 
also try print(set_value) (note the lack of parenthesis)
 
cbg
 
3:32 AM
cbg, @Skyler
 
int object is not callable
i get error
 
Okay, now change it to #@requires_role (comment it out)
then after you define set_value
 
so guys, any advice on how to write several elements of an array using csvwriter row per row
or with numpy
 
add set_value = requires_role(set_value)
@Skyler eh? row per row?
@Ming once you've done that... do you understand what the @requires_role is doing?
 
well i have like 300 columns of data per row of a csv file and instead im doing something like
print r[2],r[4],r[8],r[9],r[10],r[12],r[14],r[15],r[16],r[17],r[19],r[21]
for each line
but now I want to move from printing to writing it to a file
 
3:35 AM
ah. So you only want specific columns?
 
@WayneWerner i got cant assign function to call
 
yea
 
@Ming don't call the function, set_value = requires_role(set_value)
note the lack of parens before the =
 
oh ok
requires_role is taking in set_value as a function
 
@Skyler instead of print why not data = [...]?
 
3:36 AM
taking set_value as argument i mean
 
or just writer.writerow([...])
 
but i dont think its invoking set)value correct
 
correct - you could easily verify that by adding a print statement to set_value
 
data = r[2],r[4],r[8],r[9],r[10],r[12],r[14],r[15],r[16],r[17],r[19],r[21]
writer=csv.writer(outf)
writer.writerows(data)
 
yup. got that.
 
3:38 AM
and you can easily invoke it from requires_role by adding func(). But that would invoke the function when it's defined, which we don't want to do ;)
 
right?
 
@Skyler yeah. I'd wrap them in () or [] for clarity, but yeah, just like that
 
@WayneWerner write what?
this is all in a for loop if thats what you mean
 
data = (...)
 
oh ok
 
3:40 AM
why not though.
it is because it does not affect the global scope?
 
I'm also assuming that you're going to do something like

writer = csv.writer(outf)
for r in otherthing:
    writer.writerow(...)
 
and thus will not affect other functions.
 
It does/will. But it won't be much value to us if we're setting the value now. We want to keep the function around and change the value later
 
i see.
 
so also... note if your decorator does return func
you'll see that the original code works the same
 
3:42 AM
i did return 42, func
 
the only difference is that it prints Func is <....>
value = 42
role = 'ADMIN'


def requires_role(func):
    print('Func is ', func)
    return func


@requires_role
def set_value():
    global value
    value = 12

set_value()
print(value)
like that
you could also, instead of returning func
do

    def requires_role(func):
        def forty_two(*args,**kwargs):
            print(42)
        return forty_two
 
just want to confirm
if i put the decorateor requires_role, it invokes requires_role() function ...
but does not actually pass anything to set_value()?
also set_value() never runs correct?
 
the latter is up to requires_role
@some_func
def another_func():
    return 42

is equivalent to

another_func = some_func(another_func)
 
i see.
a decorator is just passing that decorated function as an argument to the decorator
 
bingo
that's what it's doing
the question is why? what do we gain?
 
3:51 AM
cleanliness ?
no need to call that function within other functions?
have a function with multiple decorators?
 
pretty much - and the ability to adjust the behavior of a function (or add more behavior) to a function
and yeah, you could add multiple decorators
 
value = 42
role = 'ADMIN'


def requires_role(func):
    print('Func is ', func)
    return func


@requires_role
def set_value():
    global value
    value = 12

set_value()
print(value)
sry meant to paste this
def multiply(func, a):
	return func * a

@multiply
def elementA():
	return 100

elementA()
 
(some people would argue about the cleanliness of decorators... It all depends)
 
it does not work?
 
no... you need to call the function
return func() * a
 
3:54 AM
i get error missing 1 argument a
 
ah... yeah right
so @multiply takes arguments
remember - it's like elementA = multiply(elementA)
 
yeah. but cant figure out how to pass that next argument a
 
so... are you aware that you can do something like this?
def func():
    print('hi!')

bar = func
bar()
 
yeah. I'm aware of that
 
so let's say I have the following code
def outer():
   def inner():
      return 42

???
x = func()
print(x)  #prints '42'
How do you have to modify that code to get it to work the way it's written?
 
4:02 AM
hmm.
 
here's a hint, outer as to return smoething
 
ah yes
def outer():
	def inner():
		return 42
	return inner()
print(outer())
outer = x
x = func()
print(x)
cant get this though. got error
 
outer = x is definitely wrong
you'll get a NameError there
 
I'm really just simply typing now.
 
plus, you func doesn't get defined. Let's work backwards...
 
4:06 AM
cant seem to figure out. x = func()
 
x = func()
we know we want x to contain 42 after the call
is there a function anywhere that returns 42?
 
outer()
 
that's true, now... but if you go back to the original code
 
oh wait. i think i got. it
ah.
was thinking
func():
return outer
works right?
yeahh.
got it. correct?
 
it works, but it's a little more complicated than it needs to be
try this:
def outer():
    def inner():
        return 42
    return inner

func = outer()
x = func()
print(x)
 
4:11 AM
i got ` int object is not callable`
ah. x = func works
i get what you were saying earlier. bar = func. basically assigning return value of func to bar ?
 
then you are doing return inner()
 
oh i see
is there like a best practice?
 
I should've added an argument to make things even more explicit
 
in regards to where to call the function
 
def inner(arg): return arg/2 :)
then x = func(84)
you'll see that this only works with way I wrote it - return inner, etc.
 
4:16 AM
how about this?
def outer(a):
	def inner(b):
		return 42
	return inner * a * b
but i tried doesnt work
 
nope. You can't multiply a function
inner is the name of a function
 
def outer(a):
	def inner(b):
		return 42
	return inner() * a * b
this?
 
that works but as a decorator it's useless
you can't do

func = outer()
func()
 
ah. you're right
 
you always want your decorator to return a function
 
4:20 AM
so can i pass the value of the decorator function to the original function?
@outer(10)
def func(a):
	return a
doesn't work. says int object is not callable
 
right. So let's go back to our example and build it up a little more
So, we have our decorator function
but it's not returning anything
we need to return a function, as we've seen
but we also want to check for the roles before we call the decorated function
so let's make a function with the role check that calls a function, or displays the error
Here's one:
def check_role():
    if role == 'ADMIN':
        func()
    else:
        print('You are unauthorized')
where would you put it?
 
hmm.
 
(note, that this will currently fail with set_widget)
 
def check_role(fn):
	if role == 'ADMIN':
		func()
	else:
		print('you are not authorized')

@check_role
def set_value():
	global role
	role = 'ADMIN'
like this?
 
nope. We want to keep requires_role around.
That's our decorator
 
4:31 AM
value = 42
role = 'ADMIN'

def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	return func

def check_role(fn):
	if role == 'ADMIN':
		func()
	else:
		print('you are not authorized')
@requires_role
def set_value():
    global value
    value = 12
    print('hello. set_value here')
can it be like `check_role(update_widget(setting))
if role == 'ADMIN' , THEN call the function
but your original code did not pass func() as an argument, so didnt know how you intended to call it.
 
nope, that's not a decorator (and requires the calling code to know about checking roles)
take a look at your code - where is func in scope?
 
set_value = requires_role(set_value)
func is within requires_role , so its in requires_role scope?
 
it's in scope in requires_role, yeah
 
def check_role():
	if role == 'ADMIN':
		func()
	else:
		print('you are not authorized')
this func() is within check_role()
but how to invoke it?
def check_role(func):
	if role == 'ADMIN':
		func()
	else:
		print('you are not authorized')
this?
 
where does that code belong?
 
4:36 AM
oh. did you mean to call it within requries_role
 
bingo
 
def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	return check_role()
 
well, more accurately define it
not call it
value = 42
role = 'ADMIN'



def requires_role(func):
    def check_role():
        if role == 'ADMIN':
            func()
        else:
            print('You are unauthorized')
    return check_role


@requires_role
def set_value():
    global value
    value = 12


set_value()
print(value)
change the role and you'll see that this does the right thing
 
yes.
but one thing
 
Now if you decorate set_widget you'll see that calls to it fail. Do you see why?
 
4:40 AM
alue = 42
role = 'ADMIN'

def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	return check_role()

def check_role():
	if role == 'ADMIN':
		func()
	else:
		print('you are not authorized')

@requires_role
def set_value():
    global value
    value = 12
    print('hello. set_value here')
this does not work?
func() is not within requires_role scope?
i got func is not defined
for func() in check_role()
 
it's not about execution scope, it's where the code was defined
 
i see
 
also you're calling the code on definition
even if you added check_role(func) to definition and call
 
ah ok.
 
print('Calling set_value')
set_value()
print(value)
would end out printing things in the wrong order. That's no bueno
 
4:45 AM
different from js right? closures?
 
these are closures
it's exactly like you'd find in js
 
yeah but in js this would work right
def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	return check_role()
 
*well, except with Python you can still get enclosed values, because we're all consenting adults here
I don't think so
because func isn't defined in the global scope there either
 
function apple() {
	return orange;
}

function orange() {
return 'orange'
}

console.log(apple())
this? similar?
function apple() {
	return orange();
}

function orange() {
return 'orange'
}

console.log(apple())
 
not at all
in js you'd have
function apple(func){
    return orange();
}

function orange(){
    func();
    return 'I am an orange!';
}

apple();
and that would throw an error
cause func ain't defined
 
4:54 AM
hmm.. yes.
but the check role example
def requires_role():
	def forty_two(*args, **kwargs):
		print(42)
	return check_role()

def check_role():
	if role == 'ADMIN':
		func()
	else:
		print('you are not authorized')
this will not work correct?
because you mentioned func is defined where its called. not where its invoked
 
correct. For the same reason js doesn't.
 
i see
 
@Ming func must be defined in one of the visible scopes
 
sry got sidetracked. but this works right.
value = 42
role = 'ADMIN'

def requires_role(func):
	def forty_two(*args, **kwargs):
		print(42)
	def check_role():
		if role == 'ADMIN':
			print('admin is correct')
			func()
		else:
			print('you are not authorized')
	return check_role

@requires_role
def set_value():
    global value
    value = 12
    print('hello. set_value here')

def user_has_valid_role(*roles):
    if role not in roles:
        print('Role {!r} not in required roles {!r}'.format(role, roles))
        return False
    else:
you mentioned earlier that update_widget will not work. i tried. it works.
 
not with the decorator
 
4:58 AM
admin is correct
hello. set_value here
setting1  User has valid role of ADMIN and MANAGER
[Finished in 0.1s]
 
(also you still have the role checking code in there)
 
my output
 
if you change it to the decorated code
@requires_role
def update_widget(setting):
    global widget
    widget = setting
 

« first day (2037 days earlier)      last day (2916 days later) »