The Assignment Clauses section in Python docs can be interesting.
The = operator in Python acts differently depending on the situation, but in the case when you imagine, it just binds the new object to a new local variable:
def factory(foo):
Although it may be more confusing than useful, the dis module can show you a byte code representation of a function that can show how Python works internally. Here is the disassembly of the `factory:
>>> dis.dis(factory) 4 0 LOAD_GLOBAL 0 (Foo) 3 CALL_FUNCTION 0 6 STORE_FAST 0 (foo) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE
What it is, Python loads the global Foo class by name (0) and calls it (3, the instance and call are very similar), and then stores the result in a local variable (6, see STORE_FAST ). Then it loads the default return value of None (9) and returns it (12)
What is the pythonic way of doing this? Is this a template to avoid? If this is a current error, what is it called?
Functions
Factory is rarely required in Python. In the random case, when they are needed, you simply return a new instance from your factory (instead of trying to assign it to the pass-in variable):
class Foo(object): def __init__(self): self.member = 10 pass def factory(): return Foo() aTestFoo = factory() print aTestFoo.member
source share