Python: How to refer a class inside itself? - python

Trying to refer a class inside itself. For e.g.
class Test:
FOO_DICT = {1 : Test.bar} # NameError: name 'Test' is not defined
#staticmethod
def bar():
pass
Does this usage make sense? Any better alternatives?
Thanks!

If you want the dictionary to be in the class: define the function first and remove Test:
class Test:
#staticmethod
def bar():
pass
FOO_DICT = {1: bar}

You don't need to reference the class inside itself, using bar instead of Test.bar will work fine.
class Test:
#staticmethod
def bar():
pass
FOO_DICT = {1: bar}
# You can access this outside of the class by simply using Test.FOO_DICT
print(Test.FOO_DICT)
However, there are cases where you really need to use a class in itself.
For example
class Test:
#staticmethod
def bar():
pass
def test_with_other_of_same_instance(self, other: Test):
print(other.FOO_DICT)
FOO_DICT = {1: bar}
In this case,
I want to define a method that accepts an object of the same Test class.
I want to use python's type hinting to indicate that the expected argument is an instance of Test. This allows me get editor support and also so tools like pylance and mypy can notify me of possible errors if I passed a argument of wrong data type.
As at the time of this writing, I'll get a NameError: name 'Test' is not defined.
This is because by default I can't use a class within itself (It is possible later versions of python will change its default behavior, hence we won't be needing the solution below by that time).
But if you use Python versions from 3.7+ and you can't reference a class within itself, the simple solution came with PEP 563 - Postponed evaluation of annotations. It is implemented by adding a little line of code at the first line of the file
from __future__ import annotations
# other imports or code come afterwards
class Test:
#staticmethod
def bar():
pass
def test_with_other_of_same_instance(self, other: Test):
print(other.FOO_DICT)
FOO_DICT = {1: bar}
So you can use a class within itself in python by simply including that line at the beginning of the file.
Normally, if you use pylance or any similar tool, you get a warning or error display to show you that you imported something and didn't use it. But not in the case of annotations. You don't have to worry about any warning from your editor.
Note that this must occur at the beginning of the file otherwise you get a SyntaxError and versions earlier than 3.7 won't support this.

You could move FOO_DICT = {1 : Test.bar} outside of class like this:
class Test:
#staticmethod
def bar():
pass
Test.FOO_DICT = {1: Test.bar}

Related

Method parameter type same as the method's class Python [duplicate]

Python 3.6.1, there are several ways of type hinting, in the doc string or annotation. How can I achieve this using annotation?
Say I have a class, which have a class method load to load data from somewhere, json or database for instance, and construct and return a instance of this class.
class Foo:
#classmethod
def load(cls, bar) -> Foo:
pass
I think this is quite straightforward, but python interpreter raised an error that Foo is not defined.
I know the reason, because when python loads Foo's load's function signature, the Foo class's definition is not finished, so the Foo is not defined yet.
Is this a drawback of function annotation? Can I find some way to achieve this goal, instead of using doc string to type hint, since I really like the clearness of function annotation.
You can use string literals for forward references:
import typing
class Foo:
#classmethod
def load(cls, bar) -> 'Foo':
pass
class Bar:
#classmethod
def load(cls, bar) -> Foo:
pass
print(typing.get_type_hints(Foo.load)) # {'return': <class '__main__.Foo'>}
print(typing.get_type_hints(Bar.load)) # {'return': <class '__main__.Foo'>}
From Python 3.7 this can work without making it a string, if you opt in to the "postponed evaluation" behaviour (see PEP 563) with:
from __future__ import annotations

Reuse docstring from a method in a class in python

So I have a method in a class and I have another separate function (i.e., outside the class) that want to reuse the docstring of that method. I tried something like __doc__ = <Class Name>.<Method Name>.__doc__ under the separate function but that does not work. Thus, is there a way to do so?
__doc__ needs to be assigned as a property of the new function, like this:
class C:
def foo(self):
'docstring'
def bar():
pass
bar.__doc__ = C.foo.__doc__ # NOT __doc__ = ...
assert bar.__doc__ == 'docstring'
Even this is a case, I'd use a manual copy of a docstring. Class or function could be moved around or separated to different projects. Moreso, reading a function below goesn't give me any idea what it's doing.
Please, consult with PEP-8, PEP-257 and PEP-20 for more information why this behavior is discoraged.
def myfunc():
...
myfunc.__doc__ = other_obj.__doc__

Default variable referencing own class in python

I'm trying to write something like:
class MyClass(object):
#staticmethod
def test(x, y, z=None):
if not z:
z = external_function(MyClass)
Is it possible in python to rewrite it to something like:
class MyClass(object):
#staticmethod
def test(x, y, z=external_function(MyClass)):
pass
(The second code does not work as it is referencing MyClass which is not defined at this point)
It is not possible to rewrite the code that way. The closest you can do is something like:
class MyClass:
pass
def test(x, y, z=external_function(MyClass):
pass
MyClass.test = staticmethod(test)
del test
Note that this assumes Python 3; in Python 2, you may need to fiddle around with the new module. But though this is possible, the intention of the code is very non-obvious. It is better to stick to if z is None, or to refactor your code to not need this.
It's not possible, since whatever is in the argument definition of any method, be it a static method or a normal method, is parsed and executed at class creation time, before the class object that you try to use has been created. Defaults are also evaluated at this time, as the code below demonstrates.
def say_hi():
print "Getting default value"
class MyClass(object):
print "Creating class"
#staticmethod
def test(a=say_hi()):
print "test called"
MyClass.test()
MyClass.test()
Output:
Creating class
Getting default value
test called
test called

calling class/static method from class variable in python

I'm trying to make a ImageLoader class handle the loading and processing of image resources like this:
class ImageLoader:
TileTable = __loadTileTable('image path', some other variable)
#staticmethod
def _loadTileTable(arg1, arg2):
blah blah
however, on compile i get: NameError: name '_loadTileTable' is not defined
If i replace the second line with TileTable = ImageLoader.__loadTileTable('image path', some other variable) then i get NameError: name 'ImageLoader' is not defined
As i'm going from C# to Python, static classes with static methods is what i'd use to implement this. However, i'm open to how I'd do this in general in python (that is, call static library functions that are only grouped together by their functionality).
UPDATE:
After reading both answers, I'm getting a picture that what i'm trying to do probably isn't right.
How would I go about imlementing ImageLoader so that I can do this:
Assuming that tile table returned an array
module1.py
aTile = ImageLoader.TileTable[1]
module2.py
anotherTile = ImageLoader.TileTable[2]
ideally, i'd populate TileTable just once.
Update:
Thanks for all the answers, I found my last answer to populating TileTable just once in the python modules doco
"A module can contain executable
statements as well as function
definitions. These statements are
intended to initialize the module.
They are executed only the first time
the module is imported somewhere"
As for static class, i'm going to forgo classes and just make a module level variable.
Answering just the updated question, what you would do in Python is make TileTable a variable called tile_table in a module called imageloader. There is no reason at all to put any of this inside a class.
So then you get:
module1.py
import imageloader
aTile = imageloader.tile_table[1]
module2.py
import imageloader
anotherTile = imageloader.tile_table[2]
and imageload.py looks something like:
def _loadTileTable(arg1, arg2):
pass # blah blah
tile_table = _loadTileTable('image path', other_var)
Think of a Python module as a singleton instance in other languages (which in fact it is) and you'll be able to reconcile this with any OO preconceptions you inherited from other languages.
In Python, the code in the class block is first executed, then the resultant namespace is passed to the class initializer. The code you wrote could have also been written as:
TileTable = _loadTileTable(arg1, arg2)
#staticmethod
def _loadTileTable(arg1, arg2):
pass # blah blah
ImageLoader = type('ImageLoader', (), {'TileTable': TileTable, '_loadTileTable': _loadTileTable})
del TileTable
del _loadTileTable
As you can see, the call of _loadTileTable appears before the definition of it. In your example, within the class definition, the call to _loadTileTable must come after the definition of _loadTileTable.
One possible fix is to simply re-arrange the class definition.
class ImageLoader:
def _loadTileTable(arg1, arg2):
pass # blah, blah
TileTable = _loadTileTable('image path', other_var)
Note that I removed the 'staticmethod', because at the point where _loadTileTable is called, it's being called as a function and not a method. If you really want it to be available after class initialization, you can define it as a static method after the fact.
class ImageLoader:
def _loadTileTable(arg1, arg2):
pass # blah, blah
TileTable = _loadTileTable('image path', other_var)
_loadTileTable = staticmethod(_loadTileTable)
Class-level variables which get updated are a bad, bad thing. Our default expectation is that object instances are stateful and classes are stateless.
In this case, we're trying to "magically" initialize a collection as a class variable, which is a toweringly bad idea. A collection is simply an object with simple instance-level attributes.
The magical Tile Table should not be a concealed, static part of the ImageLoader. There is no possible reason for that. It should be an argument to the ImageLoader if you want to avoid loading it more than once.
Separating these promotes testability. It's not arbitrary. It's how unit testing gets done.
What you want is this.
class ImageLoader( object ):
def __init__( self, theTileTable ):
self.tile_table= theTileTable
class TileTable( object ):
def __init__( self, path, some_other_arg ):
self.tileTable= self._loadTileTable( path, some_other_arg )
def _loadTileTable(arg1, arg2):
blah blah
No static anything. Independent units. More easily testable. No weird dependencies. No magic.
Is there a design reason you're using a static method? If so, because you're not overloading the class initialization, you'll need to declare the variable after the method definition.
But, if you do this, you'lll get a new error:
NameError: name 'arg1' is not defined
The reason for this is because you're executing the method within the class before the class is even instantiated, therefore you never have a chance to pass the arguments to the method.
So, the proper way to do this is to overload the __init__() method so that assignment to TileTable only happens when the class is constructed:
class ImageLoader(object):
def __init__(self, arg1, arg2):
self.TileTable = self._loadTileTable(arg1, arg2)
#staticmethod
def _loadTileTable(arg1, arg2):
print arg1, arg2
This gives you the ability to call ImageLoader._loadTileTable() without having an instance, but then it also allows you to create the TileTable instance variable upon creating an instance.
Using a Class method
In response to my comment about the possible need for a classmethod, here is an example that covers this:
class ImageLoader:
#classmethod
def _loadTileTable(cls, arg1, arg2):
return arg1, arg2
# We're creating the class variable outside of the class definition. If you're doing
# this in a module, no one will ever notice.
ImageLoader.TileTable = ImageLoader._loadTileTable('foo', 'bar')
There might be a better way to do this, I don't know. But I do think that this covers what you are looking for:
>>> i = ImageLoader()
>>> i
<__main__.ImageLoader instance at 0x100488f80>
>>> ImageLoader.TileTable
('foo', 'bar')
>>> i.TileTable
('foo', 'bar')
There you have an instance i that has access to the class variable, but ImageLoader.TileTable is still available from the class object without the need for an instance.

Python class has method "set", how to reference builtin set type?

If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an _____exit_____ function.
I think I know what's going on here. Are you doing something like this?
>>> class A(object):
... def set(self):
... pass
... def test(self, x=set):
... return x
...
>>> set
<type 'set'>
>>> A().test()
<function set at 0x64270>
This is a subtle problem due to the way methods are defined in classes. It is what allows you to make method aliases so easily, e.g.,
class A(object):
def some_method(self):
pass
some_other_method = some_method
You can either put set at the bottom of your class definition, or you can refer to the builtin set using __builtins__.set.
Object attributes are always accessed via a reference, so there is no way for an object attribute to shadow a builtin.
Usually method names are disambiguated from global names because you have to prefix self..
So self.set() invokes your class method and set() invokes the global set.
If this doesn't help, perhaps post the code you're having trouble with.
You can refer to built-in set as __builtins__.set.
If you run the code below you will notice that the set method of the UsesSet class does not obscure the built-in set type.
class UsesSet(object):
def set(self):
pass
def other(self):
my_set = set([1, 2])
print type(my_set), my_set
obj = UsesSet()
obj.other()
The code above outputs <type 'set'> set([1, 2]) showing that the set() method of our class has not hidden the built-in set()
If however you have module in which you have defined a function named set like below something different happens:
def set(arg):
print "This is my own set function"
class UsesSet(object):
def other(self):
my_set = set([1, 2])
print type(my_set), my_set
obj = UsesSet()
obj.other()
The code above outputs:
This is my own set function
<type 'NoneType'> None
So as you can see a module level function with the same name as a built-in hides the built-in.

Categories

Resources