Class attributes/methods without defining them Python? - python-3.x

I am seeing the code shown below for the 1st time, which I have never learned or seen anywhere else before. I have only seen Class attributes or Instance attributes. How does this one below work? Can we just add any class attributes/methods like this way?
class Globals:
pass
g = Globals()
g.tasks = []
g.diff_list = []
g.pdf_list = []
g.tstamp = None
g.terminated = False
g.num_task_retries = 4
Thank you.

Unless you specify otherwise using __slots__, Python classes are basically just wrappers over dictionaries. They can be given arbitrary attributes at any time. To prevent this, you specify __slots__ on the class, which limits the attributes that can be added, and has performance benefits as well:
class Globals:
__slots__ = ["a"]
g = Globals()
g.a = 1 # Fine
g.b = 2 # AttributeError: 'Globals' object has no attribute 'b'

Related

Accessing variables from a method in class A and using it in Class B in python3.5

I have a BaseClass and two classes (Volume and testing) which inherits from the BaseClass. The class "Volume" use a method "driving_style" from another python module. I am trying to write another method "test_Score" which wants to access variables computed in the method "driving_style" which I want to use to compute further. These results will be accessed to the class "testing" as shown.
from training import Accuracy
import ComputeData
import model
class BaseClass(object):
def __init__(self, connections):
self.Type = 'Stock'
self.A = connections.A
self.log = self.B.log
def getIDs(self, assets):
ids = pandas.Series(assets.ids, index=assets.B)
return ids
class Volume(BaseClass):
def __init__(self, connections):
BaseClass.__init__(self, connections)
self.daystrade = 30
self.high_low = True
def learning(self, data, rootClass):
params.daystrade = self.daystrade
params.high_low = self.high_low
style = Accuracy.driving_style()
return self.Object(data.universe, style)
class testing(BaseClass):
def __init__(self, connections):
BaseClass.__init__(self, connections)
def learning(self, data, rootClass):
test_score = Accuracy.test_score()
return self.Object(data.universe, test_score)
def driving_style(date, modelDays, params):
daystrade = params.daystrade
high_low = params.high_low
DriveDays = model.DateRange(date, params.daystrade)
StopBy = ComputeData.instability(DriveDays)
if high_low:
style = ma.average(StopBy)
else:
style = ma.mean(StopBy)
return style
def test_score(date, modelDays, params):
"want to access the following from the method driving_style:"
DriveDays =
StopBy =
return test_score ("which i compute using values DriveDays and StopBy and use test_score in the method learning inside
the 'class - testing' which inherits some params from the BaseClass")
You can't use locals from a call to a function that was made elsewhere and has already returned.
A bad solution is to store them as globals that you can read from later (but that get replaced on every new call). A better solution might to return the relevant info to the caller along with the existing return values (return style, DriveDays, StopBy) and somehow get it to where it needs to go. If necessary, you could wrap the function into a class and store the computed values as attributes on an instance of the class, while keeping the return type the same.
But the best solution is probably to refactor, so the stuff you want is computed by dedicated methods that you can call directly from test_score and driving_style independently, without duplicating code or creating complicated state dependencies.
In short, basically any time you think you need to access locals from another function, you're almost certainly experiencing an XY problem.

Sphinx: Share function Docstring [duplicate]

I have a class like this:
class MyBase(object):
x = 3
"""Documentation for property x"""
and another class that inherits it:
class MyObj(MyBase):
x = 0
When I use sphinx's autodoc to generate documentation, MyObj.x is not documented. Is there any way to inherit the docstring from MyBase.x? I found DocInherit but since this uses a decorator, it only works for class methods. Any way to do this with properties?
I found a workaround using the property function:
class MyBase(object):
_x = 3
x = property( lambda s: s._x, doc="Documentation for property x")
class MyObj(MyBase):
_x = 0
This is nice in that given an instance variable:
>>> m = MyObj()
>>> m.x
0
one can call help(m) and get proper documentation of property x and sphinx also picks this up correctly.
As far as I know, docstrings for attributes are not part of Python. When I try it, MyBase.x.__doc__ does not get set to the string beneath it. Docstrings only work on classes, functions and methods. If Sphinx picks up the string underneath x = 3 as a docstring, it's probably doing its own processing of the source code to get that.
If you only care for building Documentation via Sphinx. you can use:
":inherited-members:"
.. autoclass:: Noodle
:members:
:inherited-members:
This will also add the doc strings of inherited members in Sphinx Documentation.
http://sphinx-doc.org/ext/autodoc.html
As Thomas already stated, attributes do not have docstrings in Python. Sphinx however provides it's own processing allowing for attributes to be documented.
class Test(object):
#: This is an attibute docstring.
test_attr = 'test'
#property
def test_prop(self):
"""This is a property docstring."""
This results in:
class Test
Bases: object
test_attr = 'test'
This is an attibute docstring.
test_prop
This is a property docstring.

How to allow a class attribute to be access externally without class name in Python?

I defined an enum class and would like to be able to use its attributes without need to access it through class name. I mean:
class MyEnum:
ONE = 1
TWO = 2
...
if MyEnum.ONE == 1:
"Typic use"
if TWO == 2:
"My desire"
Is there a way to do this?
In my specific context, I'm calculating points externality of a window through Cohen–Sutherland algorithm, so I have the following code:
class Externality:
INSIDE = 0
LEFT = 1
RIGTH = 2
BELLOW = 4
ABOVE = 8
# And at some point:
((x, y), externality) = actual
if not Externality.INSIDE in externality:
del cohen_sutherland_list[0]
So, the needed of express Enum's name to access its items make the if statement (and the whole code) a little more verbose and redundant.
First things first: inherit from Enum.
Like everything in Python, all you need to do is assign the names:
from enum import Enum
class MyEnum(Enum):
ONE = 1
TWO = 2
ONE = MyEnum.ONE
TWO = MyEnum.TWO
That can get annoying fast, so a helper function would be nice:
def export_enum(enum_cls, env):
for member in enum_cls:
env[member.name] = member
and in use:
>>> export_enum(MyEnum, globals())
>>> TWO
<MyEnum.TWO: 2>
If you use aenum1 the export() function is already available, and can be used as a decorator:
from aenum import Enum, export
#export(globals())
class MyEnum(Enum):
ONE = 1
TWO = 2
1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

python property referring to property/attribute of member attribute?

I'm wondering if I have:
class A(object):
def __init__(self):
self.attribute = 1
self._member = 2
def _get_member(self):
return self._member
def _set_member(self, member):
self._member = member
member = property(_get_member, _set_member)
class B(object):
def __init__(self):
self._member = A()
def _get_a_member(self):
return self._member.member
def _set_a_member(self, member):
self._member.member = member
member = property(_get_a_member, _set_a_member)
Can I somehow avoid to write get/setters for A.member, and simply refer to the attribute or property of the A object?
Where the get/setters do logic, its of course needed, but if I simply wan't to expose the member/attributes of a member attribute, then writing get/setters seems like overhead.
I think even if I could write the get/setters inline that would help?
I find the question a bit unclear, however I try to explain some context.
Where the get/setters do logic, its of course needed, but if I simply wan't to expose the member/attributes of a member attribute
If there is no logic in getter/setters, then there is no need to define the attribute as a property, but the attribute can be used directly (in any context).
So
class A(object):
def __init__(self):
self.attribute = 1
self.member = 2
class B(object):
def __init__(self):
self.member = A()
B().member.member # returns 2
B().member.member = 10
In some languages, it's considered good practice to abstract instance properties with getter/setter methods, That's not necessarily the case in Python.
Python properties are useful when you'd need more control over the attribute, for example:
when there is logic (validation, etc.)
to define a readonly attribute (so only providing a getter without a setter)
Update (after the comment)
properties are not necessarily a tool to "hide" some internal implementation. Hiding in Python is a bit different than say in Java, due to very dynamic nature of Python language. It's always possible to introspect and even change objects on the fly, you can add new attributes (even methods) to objects on runtime:
b = B()
b.foo = 4 # define a new attribute on runtime
b.foo # returns 4
So Python developers rely more on conventions to hint their intentions of abstractions.
About the polymorphic members, I think it's most natural for Python classes to just share an interface, that's what's meant by Duck typing. So as long as your next implementation of A supports the same interface (provides the same methods for callers), it should not be any issue to change its implementation.
So this is what I came up with - use a method to generate the properties, with the assumption that the obj has an attribute of _member:
def generate_cls_a_property(name):
"""Small helper method for generating a 'dumb' property for the A object"""
def getter(obj):
return getattr(obj._member, name)
def setter(obj, new_value):
setattr(obj._member, name, new_value)
return property(getter, setter)
This allows me to add properties like so:
class B(object):
def __init__(self):
self._member = A()
member = generate_cls_a_property('member') # generates a dumb/pass-through property
I'll accept my own, unless someone tops it within a week.. :)

sub-classing a peewee field type to add behavior

I am trying to add the required behavior to a CharFiled or TextField so I can store a list of lists and retrieve it as a list of lists again. I am not asking for a solution rather I would like to see an example where a subclassing of an already supported field type is done as I didn't find any in the documentation or the Internet.
Do I have to do it as explained in the documents for creating a custom type?
for example:
class mylistoflists(TextField):
if yes, then what do I have to assign to field_type?
Example code (see tests/fields.py for full example):
class ListField(TextField):
def db_value(self, value):
return ','.join(value) if value else ''
def python_value(self, value):
return value.split(',') if value else []
class Todo(TestModel):
content = TextField()
tags = ListField()
class TestCustomField(ModelTestCase):
requires = [Todo]
def test_custom_field(self):
t1 = Todo.create(content='t1', tags=['t1-a', 't1-b'])
t2 = Todo.create(content='t2', tags=[])
t1_db = Todo.get(Todo.id == t1.id)
self.assertEqual(t1_db.tags, ['t1-a', 't1-b'])
t2_db = Todo.get(Todo.id == t2.id)
self.assertEqual(t2_db.tags, [])
t1_db = Todo.get(Todo.tags == Value(['t1-a', 't1-b'], unpack=False))
self.assertEqual(t1_db.id, t1.id)

Resources