Decorators - Throwing Invalid Syntax in Python - python

This may be an OS problem since I did saw on youtube videos where people were demoing how to use decorators in python in a Linux based system.
So I'm trying to play with decorators. In its usual form, you create a function of it first, and then you use the special keywoard "#func_name" in order to pass the next line of arguments into the function. This particular method of utilizing decorator is not working. I've tried in PyDev (Eclipse) and it is just reading as syntax error. I also tried the interactive Python.
Currently running windows OS 7 Python Version 2.78
Here are more specific examples
def c(n):
def d():
return "Hello world",n
return d()
c=c("of Python")
print c
output: ('Hello world', 'of Python')
#c
"of Python"
output: "of Python?"
^
SyntaxError: invalid syntax
Created a working version based on Jon's answer
def c(n):
def d():
return "Hello world" + n()
return d
#c
def decorate_this_func():
return " python"
print decorate_this_func()

then you use the special keywoard "#func_name" in order to pass the
next line of arguments into the function
That's not how decorators work. You can pass arguments to a decorator like this
#c("of python")
def decorate_this_func():
pass
But for that to work you need to tweak your decorator function a bit.
Give this a read https://stackoverflow.com/a/1594484/1843331
It's an excellent explanation of decorators, how they work, how to use arguments with decorators and much more.

Related

Str formatting in Python3.9

I am using Python 3.9 and trying to write the function
def greet(request, name):
return HttpResponse(f'Hello, {name.capitalize}!')
Using f to format the string but it is not working. Any ideas on why?
capitalize is a method of the str object.
Therefore you need to add parenthesis for it to be called:
def greet(request, name):
return HttpResponse(f'Hello, {name.capitalize()}!')
Furthermore, name.capitalize is really just the reference to the function.
Try running the following inside a python interpreter:
print(str.capitalize)
You could even return this function:
def cap_str(string):
return string.capitalize
s = "programming in python"
capitalize_s = cap_str(s)
s_cap = capitalize_s()
print(s_cap)
I don't know how this would be particularly useful, but returning a function in general is pretty useful.
Can you print the error message? I suspect your error is that you want name.capitalize() rather than name.capitalize
Ah - this has already been added!

Create functions dynamically or programmatically in python

I am trying to create functions dynamically on the fly or to create functions programmatically in python and am getting stuck at this.
def test(a,b):
print(a)
#Result:
def test(a,b,c):
print(a)
print(b,c)
I am trying it with AST module and failing to understand the AST syntax for function. I understand that a function details can be fetched using functionname.__code__.xxx. But I will be unable to make changes since it is readonly. Here is what I am trying:
I tried getting the AST dump of the above function and it didnt work.
Trying to get the string version of function definition (couldnt find reference)
I have also tried the below but feel that it may be an issue somewhere like when there is a re-assignation which makes it local:
def tests(a,b):
print(a,b)
def mytest(c):
print(a,b,c)
return mytest
def tests(a,b):
print(a,b)
def mytest(c):
print(a,b,c)
a = 10 # this will become local variable
return mytest
I am on python 3.x
Any help or any other easier way?

How to rename commands (print, os.<...>) in python?

How can you rename functions in python, like renaming print to something like say?
Things like little changes in python's code that you could potentially make into a module (for something like an addon pack).
I am not sure why you would want to rename print but this is how I would do it.
For python 3.X:
myvar = "Hello World"
say = print
say (myvar)
my example for Python 3.X does not seam to be viable for Python 2.X unless anyone else knows a way similar to my example. Otherwise here is way you can do for Python 2.X
myvar = "Hello World"
def printFun(stuff):
print(stuff)
say = printFun
say (myvar) # note that like python 3 you must put this in ()
Anytime you want to "rename" a function all you need to do is assign that function to a variable and then use that variable as the function.
Edit: On a related note you can also import the python 3 function to python 2:
# this is good to use in 2.X to help future proof your code.
# for at least the print statement
from __future__ import print_function
myvar = 'Hello World'
say = print
say (myvar)

Python magical main() signature like Perl 6

Does python have any way to easily and quickly make CLI utilities without lots of argument parsing boilerplate?
In Perl 6, the signature for the MAIN sub automagically parses command line arguments.
Is there any way to do something similar in Python without lots of boilerplate? If there is not, what would be the best way to do it? I'm thinking a function decorator that will perform some introspection and do the right thing. If there's nothing already like it, I'm thinking something like what I have below. Is this a good idea?
#MagicMain
def main(one, two=None, *args, **kwargs):
print one # Either --one or first non-dash argument
print two # Optional --arg with default value (None)
print args # Any other non-dash arguments
print kwargs # Any other --arguments
if __name__ == '__main__':
main(sys.argv)
The Baker library contains some convenient decorators to "automagically" create arg parsers from method signatures.
For example:
#baker.command
def test(start, end=None, sortby="time"):
print "start=", start, "end=", end, "sort=", sortby
$ script.py --sortby name 1
start= 1 end= sortby= name
I'm not really sure what you consider to be parsing boilerplate. The 'current' approach is to use the argparse system for python. The older system is getopt.
Simon Willison's optfunc module tries to provide the functionality you're looking for.
The opterator module handles this.
https://github.com/buchuki/opterator
Python has the getopts module for doing this.
Recently I came across the begins project for decorating and simplifying command line handling.
It seems to offer a lot of the same functions you are looking for.

GStrings in Python

Groovy has a concept of GStrings. I can write code like this:
def greeting = 'Hello World'
println """This is my first program ${greeting}"""
I can access the value of a variable from within the String.
How can I do this in Python?
--
Thanks
In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary "outside" variables from within a string. But, you can use the locals() function that returns a dictionary with all variables of the local scope.
For the actual replacement, there are many ways to do it (how unpythonic!):
greeting = "Hello World"
# Use this in versions prior to 2.6:
print("My first programm; %(greeting)s" % locals())
# Since Python 2.6, the recommended example is:
print("My first program; {greeting}".format(**locals()))
# Works in 2.x and 3.x:
from string import Template
print(Template("My first programm; $greeting").substitute(locals()))
d = {'greeting': 'Hello World'}
print "This is my first program %(greeting)s" % d
You can't exactly...
I think the closest you can really get is using standard %-based substitution, e.g:
greeting = "Hello World"
print "This is my first program %s" % greeting
Having said that, there are some fancy new classes as of Python 2.6 which can do this in different ways: check out the string documentation for 2.6, specifically from section 8.1.2 onwards to find out more.
If your trying to do templating you might want to look into Cheetah. It lets you do exactly what your talking about, same syntax and all.
http://www.cheetahtemplate.org/
In Python 2.6+ you can do:
"My name is {0}".format('Fred')
Check out PEP 3101.

Categories