0

I came across a code snippet as follows -

@classmethod
def new(cls, **props):
    '''Creates a new Thread instance, ensuring a unique _id.'''
    for i in range(5):
        try:
            thread = cls(**props)
            session(thread).flush(thread)
            return thread
            ...... continued

The name of the class it is defined is 'Thread'. This code creates a new thread object but I'm not able to understand how this particular code is trying to do that from the code in try block.

cls is a function?

phraniiac
  • 384
  • 1
  • 3
  • 16

2 Answers2

3

Now that you've edited your question, it's clear what's happening. You're method has a the decorator @classmethod. According to the docs:

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

This is (somewhat) equivalent to this:

class MyClass:
    def f(self, arg1, arg2, ...):
        cls = self.__class__
        ...

Classes in Python are callables (e.g. they can be invoked with Class()). Those two things are therefore equivalent:

a = MyClass()

and

cls = MyClass
b = cls()

In summary, cls is not a function, but a callable. Btw. you can make any object a callable by adding the special method __call__:

class A:
    def __call__(self):
        print("Woah!")

a = A()
a()   # prints Woah!
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
1

It would seem that the first argument is a class and the second is a set of key-value args (see this question describing the double star notation).

Inside the function the key-value args are then passed to the class constructor to make the variable thread.

Community
  • 1
  • 1
James Elderfield
  • 2,389
  • 1
  • 34
  • 39