In the following code why does the last line of execution give an error? - class

In the following code why does the last line of execution give an error ? Shouldn't the dot operator in x.bf() pass on the instance 'x' to the function bf ( like x.af() would ) ?
class A:
a = 6
def af (self):
return "Hello-People"
class B:
b = 7
def bf (self):
return "Bye-People"
>>> x = A()
>>> b = B()
>>> x.bf = B.bf
>>> x.bf()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bf() missing 1 required positional argument: 'self'

x.bf = B.bf is your error, because B is a class, not an instance of the object.
You can't assign x.bf directly to the class.
You need to assign x.bf to the instance 'b.bf' or instantiate the class properly
ie. Either change that line to:
# Where we instantiated class B and invoke bf via lazy loading (loading at the last possible minute)
x.bf = B().bf
or
# Use the existing instance of B and call bf
x.bf = b.bf
More information:
A and B are your classes. They don't do anything until you instantiate them.
x and b are your object instances. x is an instance of A, and b is an instance of B
Whenever you instantiate a class, you need to conform to it's constructor signature. In this case, the classes require no additional parameters besides self. However, self only gets passed if the class is invoked via ();
'x = A()' and 'b = B()' conform to that signature
The error you encountered is basically python telling you that you called something, a function or a class without passing in a required variable.

Related

How to mock a nested Function in python having some parameters in it

I'am new to pytest, I want to mock a function toMockFunction having parameter as a and b and these are initialized from system arguments in another .py file and its present inside a parent Function nestFunction So how to mock this toMockFunction from a pytest file?
# This Function is present in File A.py
def nestFunction():
abc = 1
returned_var = toMockFunction(a, b)
return returned_var
# This Function is present in File B.py
def toMockFunction(a, b):
data = pd.read_csv("a.csv")
### Some operations ###
return data
# This Function is present in File test_A.py
def test_nestFunction():
df = pd.read_csv("someFile.csv")
mocker.patch('somepath.B.toMockFunction', return_value=df)
output = nestFunction()
pd.testing.assert_frame_equal(df,output)
# Present in File A.py
if __name__ == '__main__':
a = sys.arg[1]
b = sys.arg[2]
Here sys.arg[1] and sys.arg[2] are passed as parameters from run config tab
I tried the exact code but the error is - name 'a' and 'b' are not defined
i.e its not able to mock the nested function also its aking for the input parameters
The error has nothing to do with pytest. The error as you describe states, name 'a' and 'b' are not defined. This much is true since the function definition has the following:
def nestFunction():
abc = 1
returned_var = toMockFunction(a, b)
At no point in this function is a or b defined, only abc is defined. Define a and b properly and you should get past this error.

Problem updating Locust script to 1.x: TypeError: __init__() takes 1 positional argument but 2 were given

Having changed (0.x style)
class MyBaseLocust(Locust):
def __init__(self):
super(MyLocust, self).__init__()
to (1.x style)
class MyBaseUser(User):
def __init__(self):
super(MyBaseUser, self).__init__()
I get:
[2020-07-17 14:16:33,694] XXX/CRITICAL/locust.runners: Unhandled exception in greenlet: <Greenlet at 0x28639396378: <lambda>>
Traceback (most recent call last):
...
in spawn_users
hatch()
File "c:\venv\project\lib\site-packages\locust\runners.py", line 165, in hatch
new_user = user_class(self.environment)
TypeError: __init__() takes 1 positional argument but 2 were given
(this has been asked a couple of times so I thought I'd add it here)
Here’s how it should be in 1.x
class MyBaseUser(HttpUser):
abstract = True
def __init__(self, parent):
super().__init__(parent)
(the main thing is the added parent parameter, but abstract is needed to avoid registering the base user as something that should be executed)

When overriding a trait, why the value is strange?

Demo scala code:
trait A {
val a = 3
val b = a + 2
}
trait B extends A {
override val a = 10
}
object X extends B
println(X.b)
It prints value: 2, why is it not 5 or 12?
To answer the why:
In Scala when you write
class A {
val a = 2
}
The value is initialized in the constructor of the class (the same behavior applies to traits and objects). Furthermore, superclasses are initialized before subclasses. This leads to the following behavior for your use case:
B is created (memory is reserved), with two variables a and b whose value is 0. Now the constructor of A is invoked. Because a is overwritten in a subclass and due to Scalas dynamic binding nature, it is not assigned with 2, but with the value of the subclass. You want to be it 10, but because this assignment happens in the constructor of B (which is not yet invoked) the default value 0 is assigned. Now, b is assigned. Because it is not overwritten, the value a+2 is chosen, where a is 0. Because the constructor of A is finished here, the constructor of B can be invoked, which assigns 10 to a.
Hence, a is 10 and b is 2.
To answer what to do against this behavior bug:
Don't use vals as long as you don't absolutely understand about the problems that can arise. Use defs or lazy vals instead, there values are not initialized in the constructor of a class and therefore can be easily overwritten. If you absolutely need a val in a trait, then make it final
It is possible to mark a var as initialization independent for the subclass, which can be done with var a: Type = _. This tells the compiler to not initialize this variable in the constructor of the defining class (but means that the value needs to stay mutable). It can then easily be assigned in the subclass. This gets important when the in the constructor of the superclass as method is called, that initializes a var:
class A {
f()
def f() = ()
}
class B extends A {
// don't initialize this var with anything else here or
// the later assignment will be overwritten
var b: Int = _
override def f() =
b = 5
}
new B().b // prints 5

What is adding methods to a class instead of "properly" subclassing called?

Take a simple example in python:
>>> class A(object):
... pass
...
>>> def f(self):
... print "f called"
...
>>> A.f = f
>>> a = A()
>>> a.f()
f called
So in this example, the already existing class A gets an additional (instance) function f (though overriding existing ones works just as well). In real life this would of course happen e.g. in different modules. But how is this procedure called?
Not sure I am following you, but if I do, you are talking about extension methods

Scala reflection on function parameter names

I have a class which takes a function
case class FunctionParser1Arg[T, U](func:(T => U))
def testFunc(name1:String):String = name1
val res = FunctionParser1Arg(testFunc)
I would like to know the type signature information on the function from inside the case class. I want to know both the parameter name and type. I have had success in finding the type using the runtime mirror objects, but not the name. Any suggestions?
Ok, let's say you got the symbol for the instance func points to:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{currentMirror => m}
val im = m reflect res.func // Instance Mirror
You can get the apply method from its type members:
val apply = newTermName("apply")
val applySymbol = im.symbol.typeSignature member apply
And since we know it's a method, make it a method symbol:
val applyMethod = applySymbol.asMethod
It's parameters can be found through paramss, and we know there's only one parameter on one parameter list, so we can get the first parameter of the first parameter list:
val param = applyMethod.paramss(0)(0)
Then what you are asking for is:
val name = param.name.decoded // if you want "+" instead of "$plus", for example
val type = param.typeSignature
It's possible that you think that's the wrong answer because you got x$1 instead of name1, but what is passed to the constructor is not the named function testFunc, but, instead, an anonymous function representing that method created through a process called eta expansion. You can't find out the parameter name of the method because you can't pass the method.
If that's what you need, I suggest you use a macro instead. With a macro, you'll be able to see exactly what is being passed at compile time and get the name from it.