Instantiation variation in python - python-2.7

I am vrey new to python and have to work with a given code (not my implementation), with very limited accesses (no debugger, screen prints and such).
Assuming I have the following class:
class foo ():
def __init__(self, u, v):
#some flow
def main():
#some flow
x=1
return x
main() and foo() are in the same "file.py" file. are they connected?
and I instantiate it in the following way:
import file as A
MyFoo=A.main()
In oppose to:
MyFoo=foo()
Did I call upon the __init__ function?
If so how? I see no point where it is stimulated.
If it was indeed called (and here lies the big questions) how do I assert values for u & v?
I have tried an online compiler and still didn't manage, changing u & v values. I also read this to try and understand instantiation process in python.

It would help if you stated your overall goal, but I can offer this information: __init__ is called by Python to initialize new instances of a class. If you want it called, you should say "myfoo = foo(myu,myv)". That will cause Python to invoke __new__, which will invoke __init__ for you. You should do something with u and v inside __init__, perhaps assigning them to instance attributes, like this: "self.u = u".
Here, main() is just a normal, unbound function, not an instance function or a class function of foo, not even a static function inside foo's scope, and definitely not a mainline in the C and Java sense of "mainline." If you want it to create an instance of foo, you should put "myfoo = foo(myu,myv)" inside main(project). However, the fact that you named the function "main" suggests you don't know how mainlines work in Python. See here: What does if __name__ == "__main__": do?
When you import file as A and then say "MyFoo = A.main()", all you are doing is invoking main(), which just returns 1 and does nothing with class foo. Try printing out MyFoo. You will see that it got the return value of main (which was 1), and thus MyFoo has nothing to do with class foo.
The way you are naming things suggests you are very confused. Please say your overall goal, so we can help you more.

Related

Why does decorator work like that?

I try to figure out the meaning of decorator in python, and practice a snippet as below on python console:
def print_my_name(name):
print "I am %s" %(name())
#print_my_name
def my_name():
return "Hans"
And it will come out with,
I am Hans
It never happens on normal functions.
Could anybody tell me how it works?
Thank you
A decorator takes the function definition and creates a new function that executes this function and transforms the result.
The shortest explanation that I can give is that decorators wrap your function in another function that returns a function.
This code, for example:
#decorate
def foo(a):
print a
would be equivalent to this code if you remove the decorator syntax:
def bar(a):
print a
foo = decorate(bar)
Decorators sometimes take parameters, which are passed to the dynamically generated functions to alter their output.
Another term you should read up on is closure, as that is the concept that allows decorators to work.

How to modify function's locals before calling it in python

Suppose I have defined a function like this:
def calc():
print x
And I want to inject var x into the function's local by some ways before I calling it.
This looks like I added a keyword x and I can use x in function calc() without defining it. And what x will be is defined by the outer function who calls the calc().
Maybe this is a silly question, but I just want to know is it possible to do that?
If we can't modify it's locals before calling it, can we try another way? That is suppose we use decorator or something else to modify the func()'s definition automatically to
def clac(x):
print x
Maybe in this way, we need to play with the function's bytecode?
Can someone give some advise?
This seems like a very perverse thing to do, but it is actually possible. A reference to an undefined name compiles as a global variable reference, so we just need to call the function with a different global environment. Unfortunately, the func_globals attribute of functions is read-only, so we have to play some tricks with the function's code object. Try this:
exec calc.func_code in {'x': 'blah'}
Note that the dictionary you pass will be modified by adding a '__builtins__' slot - this allows the function to access Python's built-in functions and constants.

Why does one work and one crash?

This has been driving me nuts for over a week. Below are two snippets of Lua code from a robot player in the game Bitfighter (written in C++, using a variant of LuaWrapper for binding).
When I first start the Lua script, both work exactly as expected. But after some minutes of intense object creation and destruction, variant 2 stops working, and gives me the following error:
robot.lua:253: attempt to call missing or unknown method 'getEnergy' (a nil value)
To my eyes these should function identically. Who can explain the difference?
Notes: target is a (heavy) userdata representing a C++ object. getEnergy and getHealth are properly registered C++ functions. I can reproduce this differing behavior easily. This is Lua 5.1, using the luavec mod.
Variant 1 - always works
local mt = getmetatable(target)
local pow = mt.getEnergy(target) + mt.getHealth(target)
Variant 2 - starts failing after script has been running for an arbitrary amount of time
local pow = target:getEnergy() + target:getHealth()
To track what happens when it stops working you can wrap the call in pcall and explore what happened with the target value:
local ok, res = pcall(function() return target:getEnergy() + target:getHealth() end)
if not ok then
local s = "Invalid target value: "..tostring(target).." "..type(target).."\n"
for k, v in pairs(target) do s = s.."target "..tostring(k).." "..tostring(v).."\n" end
for k, v in pairs(getmetatable(target)) do s = s.."meta "..tostring(k).." "..tostring(v).."\n" end
-- add anything else that helps you figure out what happened to target
error(res..s)
end
local pow = res
I strongly suspect the issue is that you have a class or struct similar to this:
struct Foo
{
Bar bar;
// Other fields follow
}
And that you've exposed both Foo and Bar to Lua via LuaWrapper. The important bit here is that bar is the first field on your Foo struct. Alternatively, you may have some class that inherits from some other base class and both the derived and base class are exposed to LuaWrapper.
LuaWrapper uses an function called an Identifier to uniquely track each object (like whether or not the given object has already been added to the Lua state). By default it uses the object address as a key. In cases like the one posed above it is possible that both Foo and Bar have the same address in memory, and thus LuaWrapper can get confused.
This may result in grabbing the wrong object's metatable when attempting to look up a method. Clearly, since it's looking at the wrong metatable it won't find the method you want, and so it will appear as if your metatable has mysteriously lost entries.
I've checked in a change that tracks each object's data per-type rather than in one giant pile. If you update your copy LuaWrapper to latest one from the repository I'm fairly certain your problem will be fixed.
When you say it stops working at some stage, but works fine before... Could it be that you overwrite the .getEnergy function anywhere at runtime?
Maybe you're running a foo.getEnergy = nil instead of a foo.getEnergy == nil somewhere? Sounds like it might be a late initialization gone awry :)

What code is executed when a class is being defined?

When I import a module that has a class, what code is executed when that class is first read and the class object created? Is there any way I can influence what happens?
Edit: I realize my question might be a bit too general...
I'm looking for something more low-level which will allow me to do introspection from C++. I extend my C++ application with Python. I have some classes that are defined in C++ and exposed in Python. The user can inherit from these classes in the scripts and I want to be able to grab details about them when they are first defined.
Many possible things can happen. The most basic:
The contents of the class block are executed when the it is first read.
To see this in action, this example:
class Foo(object):
print "bar"
def __init__(self):
print "baz"
Will print bar when the module is imported.
If a class has a metaclass defined, the metaclasses __new__ function will run after the classes block of code is run.
Example:
class MyMeta(type):
def __new__(mcs, name, bases, kwargs):
print "I'm the metaclass, just checking in."
return type.__new__(mcs, name, bases, kwargs)
class Foo(object):
__metaclass__ = MyMeta
print "I'm the Foo class"
Output:
I'm the Foo class
I'm the metaclass, just checking in.
I'm sure other bits can run as well, these are just what I am familiar with.
Defining a class A that inherits from B and C executes: A = type('A', (B, C), m where m is a dictionary containing the members of the class.
You can influence the process using metaclass programming. There are no shortage of blog posts and tutorials on the subject.
You might be interested in metaclasses, which are classes that control the creation of classes.
The code in a class definition is executed just like any other code but any variables created (including function definitions) will be in the context of the class instead of global. This means that you can change the class definition dynamically by adding conditional code:
class A(object):
if 1==2:
def f(self):
print "the world has gone mad"
else:
def f(self):
print "sanity rules"
>>> a = A()
>>> a.f()
sanity rules
>>>
However I have never seen this done, and can't think of a reason for doing it - it feels rather unpythonic.
As others have pointed out there are lots of other ways of modifying the behaviour of a class including metaclasses, inheritance and class decorators.
Python is interpreted, so when a Python module is imported any class code at the module level is run, along with those classes' meta-classes -- this is so the classes will exist.
C++ is compiled: the classes already exist when they are imported; there is no way to control how they are created as they are already created.

Saving state of complex, scripted objects

In C++ I have the following two classes that I expose (using Boost) to Python:
struct Foo {
// Empty
};
struct FooContainer {
// I use boost::shared_ptr for compatibility with Boost.Python
vector<boost::shared_ptr<Foo>> foos_;
};
In the Python side I might create a special type of Foo that actually does something instead of being just an empty class, and then add it to a FooContainer:
class Useful(Foo):
def __init__(self, a, b):
self.a = a
self.b = b
x = Useful(3, 5);
# Add 'x' to a `FooContainer`
Back in the C++ side, the FooContainer now has some Foos, but it doesn't know or care that they are from Python. The application runs for a while and the data in the Foo objects changes...
Then I decide I want to save the state of my program so I can load it at a later time. But the problem is that FooContainer doesn't know much about its Foo objects, it doesn't even know that they come from Python and I wouldn't want to pollute my FooContainer with data that doesn't really belong in it (single-responsibility principle and all that).
Do you have any advice on how I should organize my application such that saving and loading data, as well as loading fresh data (ie. not from a state that I saved in the past) can be done in a clear way?
You can use boost::python/pickle, and save the data from python. I only have limited experience with the pickling suite, but it should work provided you override appropriate pickling methods in your classes derived in python (see my answer to this question).
You already have python code that creates the Foos, lets call it populateFoos and somehow you have your program call it.
Now the next thing you need is a storeFoos and loadFoos function that does the saving and loading. If you want to keep it generic define them as storeFunc and loadFunc (or callback, depending on the context).
Depending on your program structure you might also need to keep in python a list of all foos created (or associated to a container).