Suppress warning Eclipse when developing with Pydev - python

I want to suppress Eclipse warnings when defining decorators.
For example:
def tool_wrapper(func):
def inner(self):
cmd="test"
cmd+=func(self)
return inner
#tool_wrapper
def list_peer(self):
return "testing "
I get warning on a decorator definition:
"Method 'tool_wrapper' should have self as first parameter
I define the decorator inside a class, so this is the only way it's working properly.
Thanks

Just define your decorator outside the class and pass the instance as an argument, it will work just as fine.
def tool_wrapper(func):
def inner(inst): # inst : instance of the object
cmd="test"
cmd+=func(inst)
return cmd
return inner
class Test():
def __init__(self):
pass
#tool_wrapper
def list_peer(self):
return "testing "
if __name__ == '__main__':
t = Test()
print t.list_peer()
This script prints testtesting

Related

Overwrite a function in a python library

I want to overwrite a function in a python library.
Example:
This is my library, already compiled, in example.py
def my_function():
return "Hello World"
if __name__ == "__main__":
return my_function()
Of course if I run example.py it prints "Hello World".
What I want to do is to be able to overwrite my_function() in terms to return another stuff (Example "Hello ...") and be able to run example.py and print "Hello ..."
I need that because I want to deliver a library used by my users in which they can customize some code, like in the example. How can I do it ?
---EDIT---
The users will not touch the "main" in example.py.
in the example.py I call my_function() but I want to overwrite my_function() in the example.py in the user code.
When your users will import the module they will do:
import the_module
to use your function then they would do
the_module.my_function()
This is technically possible to do something like
import the_module
def replacement():
print("something else")
the_module.my_function = replacement
But I don’t see any added value here between this and them just creating the function themselves.
Where it can come with value, it is in OOP, where then you will create a class with a set of given method, and one can inherit your class and override some methods, still keeping others.
class Animal:
def say(self):
print("something")
def sleep(self):
print("sleeping")
class Cat(Animal):
def say(self):
print("Miaou")
I'm sure there can be some hack to do this with functions, but better to use Object-Oriented-Programming style to support this functionality in an understandable way. You can define a class containing your functions, and users can override some functions by inheriting this class and implmenting their own variants of the functions:
# my_library.py
class LibraryFunctionality:
def my_function():
return "My function"
def my_other_function():
return "My other function"
then users could do
# user.py
import my_library
class MyFunctionality(LibraryFunctionality):
def my_function():
return "My unique function"
MyFunctionality.my_function() # returns "My unique function"
MyFunctionality.my_other_function() # returns "My other function"
If you have a large method, that you want to let users to override by parts (without requiring them to repeat the same implementation), you can use a "Template method" design pattern, where you split a big method into many functions for all the steps, and then users can override some steps selectively. For example something as big as this:
# my_library.py
class LibraryFunctionality:
def before_initialization_step():
pass
def initialization_step():
return "My"
def after_initialization_step(state):
return state
def before_work_step(state):
return state
def work_step(state):
return state + " function"
def after_work_step(state):
return state
def before_return_step(state):
return state
def return_step(state):
return state
def my_function():
LibraryFunctionality.before_initialization_step()
state = LibraryFunctionality.initialization_step()
state = LibraryFunctionality.after_initialization_step(state)
state = LibraryFunctionality.before_work_step(state)
state = LibraryFunctionality.work_step(state)
state = LibraryFunctionality.after_work_step(state)
state = LibraryFunctionality.before_return_step(state)
return LibraryFunctionality.return_step(state)
Then users can override specific steps as I've already shown:
# user.py
import my_library
class MyFunctionality(LibraryFunctionality):
def before_work_step(state):
return state + " unique"
LibraryFunctionality.my_function() # returns "My function"
MyFunctionality.my_function() # returns "My unique function"

Shortcut to and/or avoiding the "self" reference to a method within other methods of the same class

Consider a trivial print helper method - that has the intention to reduce typing / clutter for a specifically formatted output structure:
class MyClass(object):
def p(self, msg,o=None):
import datetime
omsg = ": %s" %repr(o) if o is not None else ""
print("[%s] %s%s\n" %(str(datetime.datetime.now()).split('.')[0], msg, omsg))
The point of making it short/sweet was not to then type
self.p('Hello world')
But is that the only option?
Note: I want to distribute this class within a small team - and not add a function p() to their namespaces.
If you don't use self anywhere in the method you can decorate it with #staticmethod and omit the self arg
https://docs.python.org/2/library/functions.html#staticmethod
class MyClass(object):
#staticmethod
def p(msg, o=None):
import datetime
omsg = ": %s" %repr(o) if o is not None else ""
print("[%s] %s%s\n" %(str(datetime.datetime.now()).split('.')[0], msg, omsg))
You can still call it via self.p(...) from within other methods on instances of the class
You can also call it directly from MyClass.p(...)

Python: Indent print output from class

How can I indent the print output on the command line from a class that is called? I can't edit the class file to add tabs to each print().
So I would call the imported class in mypythonthing.py:
print('Calling class')
MyClass()
All the print output would then be indented, or have something prepended to it.
e.g.
$ python mypythonthing.py
$ Running your python script...
$ Calling class
$ > The print output from MyClass is indented
$ > Exiting MyClass
$
Patch the built-in print function to prefix each line with your indentation.
import builtins
def print(*args, **kwargs):
builtins.print(" > ", *args, **kwargs)
If you can put the code that should be indented inside (one or more) functions, then you can use a decorator to wrap these functions.
Then any invocation of print inside these function will be indented.
Also, you will only need to declare this function in your main script, and not anywhere else.
Example -
import builtins
import another # for demo purposes only
# This will override the default `print` function.
# Invoking it as a decorator will automatically perform
# initialisation and cleanup. There is also never a need
# to modify this.
def indent(f):
def closure():
old = builtins.print
builtins.print = lambda x, *args, **kwargs: old("\t>", x, *args, **kwargs)
f()
builtins.print = old
return closure
some_number = "100"
# Example function, note decorator usage.
# This function may **not** take any parameters!
# It may however, use any variables declared before it.
#indent
def indentedStuffGoesHere():
print("Inside `indentedStuffGoesHere`")
print(some_number)
another.Foo().bar()
another.stuff()
print("entering special block")
indentedStuffGoesHere()
print("done")
another.py
def stuff():
print("TESTING stuff")
class Foo:
def bar(self):
print("HELLO FROM FOO")
Output:
entering special block
> Inside `indentedStuffGoesHere`
> 100
> HELLO FROM FOO
> TESTING stuff
done
i think what you might be looking for is textwrap:
textwrap docs
so as an example:
wrapper = textwrap.TextWrapper(width=preferredWidth, subsequent_indent='\t')
message = "asdf" * 50
print wrapper.fill(message)

variables as decorator arguments

I have found out that decorator arguments are passed at decorator definition rather than invocation like with functions.
Now I wonder if it is possible to make the decorater get the value of a variable at runtime like this, the decorater should print the current value of state instead of the one it head at definition:
def deco(msg):
def decorater(func):
def wrapper(*args, **kwargs):
print msg
func(*args, **kwargs)
return wrapper
return decorater
def func():
local = {
"state": None
}
#deco(local["state"])
def test():
pass
def setState(newState):
local["state"] = newState
setState("start")
test()
setState("test")
test()
func()
In your example, deco() is a decorator factory; you're creating the decorator which will then immediately be invoked. More generally, you invoke a decorator at the time that you're defining the function that you're decorating.
You can do what you're trying to do with minimal changes by just not passing in state, and accessing it as a global from within wrapper(), in which case you don't need deco(); you could just use #decorator directly. That said, I think there are better ways to do what you're trying to do.
John you should read this. In python, the variable is not the object. You question, is it "possible to make the decorator get the value of a variable at runtime", doesn't make sense because of python's scoping rules. The decorator function does not generally have access to the scope where state is defined. There are several ways you could get the behavior you want though.
Without knowing the specifics of what you're trying to do, here are two that might work. The first uses closure:
state = None
def with_closure(f):
def helper(*args, **kwargs):
# state is in scope for this function
print "Current state is: {}.".format(state)
return f(*args, **kwargs)
return helper
#with_closure
def foo():
return "something"
Or you could make an object to keep track of state:
class StateHolder:
def set_state(self, state):
self.state = state
def with_state_object(state_object):
def decorator(f):
def helper(*args, **kwargs):
print "Current state is: {}.".format(state_object.state)
return f(*args, **kwargs)
return helper
return decorator
global_state = StateHolder()
global_state.set_state("some state")
#with_state_object(global_state)
def foo():
return "something"

Why is this working in Python nosetests when logically it should not

class TestUM:
#classmethod
def setup_class(will):
""" Setup Class"""
will.var = "TEST"
def setup(this):
""" Setup """
print this.var
def test_number(work):
""" Method """
print work.var
def teardown(orr):
""" Teardown """
print orr.var
#classmethod
def teardown_class(nott):
""" Teardown Class """
print nott.var
Run it as
nosetests -v -s test.py
I am not a Python expert but I cannot figure out why the above code works flawlessly using nose. Every print prints "TEST". What exactly is happening here.
In instance methods, the first argument is the instance itself.
In class methods, the first argument is the class itself.
In your case, rather than name that argument self or cls (the convention), you've named it this, work, orr, and nott. But they're all getting the same argument regardless of the name of the argument.
You've successfully set the attribute var to "TEST", so they all see it correctly.
Example functions without the use of classes:
def test1(attribute):
print attribute
def test2(name):
print name
def test3(cls):
print cls
def test4(self):
print self
Calling those functions:
>>> test1('hello')
hello
>>> test2('hello')
hello
>>> test3('hello')
hello
>>> test4('hello')
hello
The name of the argument doesn't matter. All that matters is what the argument is pointing at, which is always the instance or class

Categories

Resources