Add additional operations to existing method which is in Python module - python-3.x

I have a python module which has several methods:
module.py
def a():
return "This is a method"
I want to add some additional functionality to method a by calling it from script to avoid modification in module itself.
How can I add additional operations or arguments to that module calling it from script?
For example I imported module.py in my script and in that script I add two arguments to method "a" and addition of those arguments in addition to:
return "This is a method"

Well, you cannot really change any imported methods as far as I am aware. That does not mean it is completely impossible, I just wouldn't know how.
Question is though if that is actually what you want (as I believe it is a very uncommon way of handling code and I am guessing not an advisable one)?
Could it be that what you actually want to achieve is something more like this:
module_script.py
def a(variable):
return_value = "This is a " + str(variable) + " method!"
return return_value
second_script.py
import module_script
print(module_script.a("nice"))
The output of the second script would be:
"This is a nice method!"

Related

How can I accept only some strings in Python function?

I want to make it like this:
>>> myfunc("strawberry")
ok
# myfunc only works with strawberry
I know that most people will answer with:
def myfunc(something):
if something == "strawberry":
print("ok")
But I want to do all this in the parameter setting.
Like, kind of like this:
def myfunc(something: OnlyThese["strawberry", "cake"]:
print("ok")
Although the code above is very incorrect, I want to see if Python already has a feature like this.
Don't believe there is a way to do what you are wanting to do without writing code in the function body.
I found answers to a similar question at
enforce arguments to a specific list of values

Mocking an Assert statement

I am teaching an introductory python course (python 3+Jupyter), and have been formulating assignments using nbgrader. For those not familiar, this basically means marking student's code via a set of assert statements. If the assert doesn't pass, they don't get the mark.
One of the tests that I want to perform is to check that students are writing their own tests. As a very simple example, let's imagine that they're supposed to be defining my_function, and all the tests that they want to run on it are supposed to be a series of assert statements inside a function do_tests() which will return True if all the tests pass.
One thing that I can obviously require of their code is that do_tests() passes simply by calling assert do_tests(). I can also check that it fails if I del my_function. However, I also want to check a bit more detail about the content of do_tests(). As a first step, I simply wanted to count the number of assert statements that they have used within the definition, and was intending to use unittest.mock.patch, trying to adapt the code from here. However, I could not figure out how to mock assert. I tried something like
from unittest.mock import patch
with patch('__main__.assert') as mock_assert:
do_tests()
but I just get an error that main does not have a method assert, and couldn't work out what module assert should be a part of.
As a crude interim, I have ended up doing
import inspect
lines = inspect.getsource(do_tests)
assert lines.count("\n assert")>=3,"You don't appear to have enough assert statements"
but obviously that doesn't give me access to any other features that mocking might offer.

Using a commandline argument to call a class method

Aplogies if I have the terminology all wrong; I am still learning the basics of Python. I have been unable to google this issue, probably in large part because I don't know the terminology..
So. I have built a class within a .py script with LOTS of methods/functions. To keep this remotely simple, I want to call these from a commandline argument. I have no idea how to explain it, and I can't find anhy examples, so I will try to demo it:
Take for example mute_on as the function that I want to call. I run the script with the function/method in the argument, like:
python3 ./myscript.py mute_on
I assume we'd import sys(?), define the class and the function, and create the relevant object from the class:
import sys
class TelnetAVR(PioneerDevice):
def mute_on(self, mute):
self.telnet_command("MO")
mypioneer = PioneerDevice('Pioneer AVR', '192.168.2.89', 8102, 10)
...and lastly I would like the commandline argument to call the method/function - instead of calling it explicitly like:
mypioneer.mute_volume()
..I want to use the arg (sys.argv[1]) to dynamically call the function, like:
mypioneer.{sys.argv[1]}()
Any ideas, kind people? I have been auto-referred to What is getattr() exactly and how do I use it? but I have no idea how that information can help me here.
I have tried setting cmnd = 'turn_off' and then the following failed...;
getattr(mypioneer, str(cmnd))
getattr(mypioneer, cmnd)
Thanks!
This answer seems a little basic, but I cannot complain as to its efficacy;
mypioneer = PioneerDevice('Pioneer AVR', '192.168.2.89', 8102, 10)
exp = 'mypioneer.' + sys.argv[1] + '()'
print('Executing: ' + exp )
exec(exp)
I gave up loking for a graceful answer, and simply constructed a string that I wanted to execute (exp) based on the commandline argument. Works great.. Home Assistant can use the same script to call 50 telnet controls over my Pioneer AVR.

Enter new variable as argument

I want to create a function that takes some chain of characters as an argument, and uses it as a str object.
def useless_function(argument) :
print(argument)
useless_function(banana)
--> NameError: name 'banana' is not defined
So this is what I did : I created a decorator that turns whatever I enter as argument into a str my function can print.
def decorator(f) :
def wrapper(arg_f) :
str_arg = str(arg)
f(str_arg)
return wrapper
So now I can decorate useless_function with my decorator, and useless_function(banana) will print 'banana'. And it will work with whatever it enter as an argument of useless_function.
My question is : is there a more elegant way or a simpler and faster way to do this automatic transformation into a string that can be used as an argument ?
Can you please elaborate because I don't understand what it is that you are looking for or saying.
If you mean: inside a function can you do input("variable")? Then the answer is yes. It is just essentially raw_input() from python2. The input from your keyboard will always be a str if I am not mistaken.
Update after edited post:
It is still not any more clear what you are trying to do.
At the end of the function, you do return * but I assume you know this.
I am really confused, but have you considered just doing str(argument)? As in takes_argument(str(argument))
2nd Update after 2nd edit:
I think I finally understand what you are trying to do, but I might be wrong.
Now, the problem is that def useless_function(argument) : will expect argument to be defined as a variable with some value(s). I am not aware of any other way than actually putting "argument" to tell python that what you are inserting is a string of characters rather than trying to reference some variable and its value. It is the same case as with print('something'), if I were to put print(something), python would try to look up the variable called something which you haven't defined.
Hope that makes sense.

Python 3: Choosing the name of a class returned from a function

Here's my sample code:
def Wrapper(SomeClass):
class WrapperClass(SomeClass):
pass
return WrapperClass
class Thing:
pass
x=Wrapper(Thing)()
print(type(x))
This prints the very ugly (and, more importantly, unclear)
__main__.Wrapper.<locals>.WrapperClass
I know why __main__ is there and I have no problem with it.
However, I'd like to change things so that my print statement gave something that was reflective of the particular class passed into the Wrapper function.
For example, is there a way to change my code so that instead it prints:
__main__.WrapperClass.Thing
Any help would be appreciated.
I ended up being able to solve the problem by using the type constructor.

Resources