self-documenting Python code [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have the following piece of Python:
class CollectorGUI(Gtk.Window):
def __init__(self, prefill, flags, data_to_return):
"""prefill should be an instance of the Prefill class"""
self.prefill = prefill
self.flags = flags
self.data_to_return = data_to_return
......
My question is: (1) how to get rid of the documentation string? I want my code to be self-documenting; (2) how to get rid of these three lines:
self.prefill = prefill
self.flags = flags
self.data_to_return = data_to_return
Is there an abbreviation?

The Prefill requirement can be documented in the method signature using function annotations:
class CollectorGUI(Gtk.Window):
def __init__(self, prefill: Prefill, flags, data_to_return):
Annotations are discoverable at runtime, just like the docstring is. Annotations are not enforced (they are meant as a more generic stepping stone for different use cases) but are immediately obvious in the signature.
You can then optionally enforce it explicitly by asserting the type:
assert isinstance(prefill, Prefill), 'prefill must be an instance of Prefill'
As for auto-setting your attributes from the function arguments, that's answered elsewhere: What is the best way to do automatic attribute assignment in Python, and is it a good idea?

While you could use inspect to automatically create attributes from the arguments in the method's signature, it would obfuscate the perfectly readable code you have now.
One look at the constructor tells me that the class at least has the attributes prefill, flags, and data_to_return.
Making explicit code implicit is often not a good idea.
But if you insist:
import inspect
class C(object):
def __init__(self, a, b, c):
spec = inspect.getargspec(getattr(C, "__init__"))
for arg in spec.args[1:]:
setattr(self, arg, locals()[arg])
c = C(1, 2, 3)
print c.a
print c.b
print c.c

Related

Python class fuction that takes self variable as argument [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to write a function that sets a self variable to None, but it feels very wrong to write a million functions for each variable.
I want to do something like:
class MyClass():
def __init__(self):
self.duck = None
self.dog = None
def makeduck(self):
self.duck = "Duck"
def makedog(self):
self.dog = "Dog"
def deleteVar(self,var):
self.var = None # or del self.var
I want to do this because the variables tend to be very large and I don't want to overload my ram so I have to delete some not needed vars depending on the context.
It is indeed possible.
Although having a clear separation between what should be program structure: variables, and data: text inside strings, Python allows one to retrieve and operate on variables or attributes given their name.
In this case, you will want to use the setattr and delattrcalls: both take an instance, an attribute name, given as textual data (a string), and operate on them like the corresponding assignment (self.var = xxx) and deleting (del self.var ). statements (but, as you intend to use, with "var" being a variable containign the actual attribute name).
def deleteVar(self, var):
# setattr(self, var, None). #<- sets attribute to None
delattr(self, var). # <- deletes attribute.
(for completeness: there is also the getattr call which allows attribute retrieval on the same bases)
That said: the memory usage of hard-coded variables, even if you have tens of them, will likely be negligible in a Python process.
Having tens of different "deleter" methods, however, would indeed be clumsy, and there are situations were your code might be more elegant by passing your attributes as data, as you intent.

Is it a good practice to implement a singleton-like class using class attributes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a class that contains some variables/states.
I would like to share those states with many other classes in my code.
I looked online and I saw that modules and singleton classes are a good way to this. I ended up creating a class and storing all the data as class attributes and accessing it via the class it self, like the example:
# foo.py
class Foo(object):
varx=45
def foo(x):
Foo.varx = x
And I would import the data as:
# bar.py
from foo import Foo
print(Foo.varx) #45
Foo.foo(5)
print(Foo.varx) #5
I would like to know if using classes attributes like this is an anti-pattern, or if there is a downside I am not seeing in this implementation.
Since your foo method is altering the state of the class Foo (rather than the state of any one instance of Foo), it would be more pythonic to use a classmethod in this case. Also, note that there is no need to explicitly inherit from object, as all python classes implicitly inherit from object.
class Foo:
varx = 45
#classmethod
def foo(cls, x):
cls.varx = x
Your current implementation of the foo method has the name of the class hardcoded into the implementation, which means that the implementation would break if you changed the name of the class. The implementation would also break if you had another class inheriting from Foo which you wanted to be able to implement the methods of Foo, as the class inheriting from Foo would have a different name.

can a self variable be defined inside the for loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
can a self variable be defined inside the for loop? it is not defined anywhere before.
I am confused over its usage. the link from where the code is attached below.
def initialize_nb_dict(self):
self.nb_dict = {}
for label in self.labels:
self.nb_dict[label] = defaultdict(list)
https://github.com/taspinar/siml/blob/master/notebooks/Naive_Bayes.ipynb
Yes, it can. self is the class instance; you can create and set attributes. In the same way that you can do:
>>> class A: pass
...
>>> a = A()
>>> a.nb_dict = {}
>>> a.nb_dict[1] = 2
>>> a.nb_dict
{1: 2}
Within the scope of the method initialize_nb_dict(), self is the instance (like a above.)
There's nothing special about self, except that it is used by convention to refer to the instance for instance methods. (You could even call a as self, but it would be unconventional to name an instance self outside of an instance method.)
One other minor point on terminology: you say "can a self variable be defined." It's probably more accurate to say that an attribute of self is being set, rather than that self is being defined; it's "defined" when the instance is implicitly passed as self to the method.

Python vs Ruby class methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The following two Ruby and Python codes are examples of class methods. Why does python allow accessing class methods through objects but ruby doesn't ?
Python code
class student:
b = 78
#classmethod
def foo(var):
return var.b
z = student()
print z.foo() # => 78
Ruby Code
class Student
##b = 78
def self.foo
##b
end
end
z = Student.new
puts z.foo # => -e:20:in `<main>': undefined method `foo' for #<Student:0x007ff4f98ab9e8> (NoMethodError)
An answer for the ruby side of your question: Ruby does allow accessing class methods through objects via a reader for the class:
class Student
##b = 78
def self.foo
##b
end
end
z = Student.new
puts z.class.foo
z.class returns the class of the object (in this case it is Student).
class Student
end
z = Student.new
puts z.class #Student
puts z.class.class #Class
From Ruby doc Object#display:
display(port=$>)
Prints obj on the given port (default $>). Equivalent to:
def display(port=$>)
port.write self
end
So it just displays the receiver, which is a Student instance. I don't see how this is relevant to class methods.
Calling the class method Student.display is in fact possible:
z.class.display
Ruby doesn't have class methods, only instance methods. In your case, foo is in instance method of the singleton class of Student.
Once you understand that there is no such thing as a class method in Ruby, only instance methods, it should be immediately obvious why calling an instance on a completely different instance cannot possibly work.

use functions in a class - python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a couple of functions defined in my code and I want to be able to call them in one of my class.
I want to pass one of their name as an argument so I can select the right function to call in my class.
I looked for such things on internet but what I found is how to call a function defined in a class inside the same or another class. I can't define my functions inside my class because they also call other functions
So there's not too much but there's my code :
class _fonction_use_:
def __init__(self,pos,function):
self.pos=pos
self.function=function
Where "function" would be the name of one of my functions defined outside the class.
So, if fonction_use belong to this class, I want something like fonction_use.function to return the function I would assigned it before.
Since functions are first class objects, you can pass them directly to your class.
def somefunc():
pass # do something
class MyClass(object):
def __init__(self, pos, function):
self.pos = pos
self.function = function
myclass = MyClass(0, somefunc)

Categories