I've recently started working at a company doing work in Python, and in their code they have a class which defines a handful of functions that do nothing, and return nothing. Code that is pretty much exactly
...
...
def foo(self):
return
I'm really confused as to why anyone would do that, and my manager is not around for me to ask. Would one do this for the sake of abstraction for child classes? A signal that the function will be overridden in the future? The class I'm looking at in particular inherits from a base class that does not contain any of the functions that are returning nothing, so I know that at least this class isn't doing some kind of weird function overriding.
Sometimes, if a class is meant to be used interchangeably with another class in the API, it can make sense to provide functions that don't do much (or anything). Depending on the API though, I would typically expect these functions to return something like NotImplemented.
Or, maybe somebody didn't get enough sleep the night before and forgot what they were typing ... or got called away to a meeting without finishing what they were working on ...
Ultimately, nobody can know the actual reason without having a good knowledge of the code you're working with. Basically -- I'd wait for your boss or a co-worker to come around and ask.
If the functions have meaningful names, then it could be a skeleton for future intended functionality.
Related
I struggle to understand the use of interfaces in C#.
This is likely because I come from Python and it isn't used there.
I don't understand other explanations as they don't fully answer my questions about interfaces. e.g. The purpose of interfaces continued
From what I understand, Interfaces tell a class what it can do, not how to do it. This means at some point the class has to be told how to do the methods.
If this is the case, what's the point in interfaces? Why not just have the definition of the method in the class?
The only benefit I see is to keep it clear what classes can/can't do, but at the cost of not DRY code?
I know that Python doesn't need interfaces and I think this limits my understanding, but can't quite figure it out why.
It is used in python, in the form (usually) of abstract classes.
The purpose varies, in java they solve multiple inheritance, in python they act as a contract between 2 classes.
Class A does something and a part of that something involves class B. Class B can be implemented in several ways, so instead of making 10 different classes and HOPE they will be used properly, you make them inherit from an abstract class (an interface) and you ensure they MUST implement all the methods defined as abstract. (NOTE IF THEY DON'T IMPLEMENT ANY OF THE METHODS IT WILL CRASH AT BUILD TIME, WHEN YOU INSTALL THE PACKAGE, NOT WHEN YOU RUN IT WHICH IS VERY IMPORTANT IN MIDDLE/LARGE-SIZE PROJECTS).
You also know that ANY class that implements those methods will work with the class that uses it. This sounds trivial, but the business side LOVES it because it means you can outsource part of your code and it will connect and work with the rest of your code.
From what I understand, Interfaces tell a class what it can do, not how to do it. This means at some point the class has to be told how to do the methods.
They actually tell it what it MUST do, as to how they do it we don't care.
If this is the case, what's the point in interfaces? Why not just have the definition of the method in the class?
That is not the point but yes, absolutely you need the definition of the method in the class that inherits from the interface.
Lets give you a more concrete example.
Imagine you have a python framework that runs some tasks. The tasks can run locally (in the same computer where the python framework is running), they can run on a distributed system, by submitting them to some central scheduler, they can run in a docker container, on Amazon Web services .... you get the idea.
All you need is an interface (an abstract class in python) that has a run_task method, as to which one you use is up to you.
e.g:
class Runner:
__metaclass__ = abc.ABCMeta
#abstractmethod
def run_task(self, task_command):
return
class LocalRunner(Runner):
def run_task(self, task_command):
subprocess.call(task_command)
class SlurmRunner(Runner):
def run_task(self, task_command):
subprocess.call('sbatch ' + task_command)
Now thge important bit, as you may be asking Why the ^$^$% do I need all these
complications? (probably you don't if yopur project is small enough, but there is a breakpoint depending on size where you almost HAVE to start using these things).
The class that uses the runner ONLY needs to understand the interface, e.g. you have a Task class, that class can delegate the execution of the task to the TaskRunner, as to which one is implemented you DON'T care, they are in a sense polymorphic.
class Task:
def __init__(self, task_runner):
self.task_runner = task_runner
self.task_command = 'ls'
def run_this_task(self):
self.task_runner.run_task(self.task_command)
And, if you are some programmer your boss can tell you, I need a new class that executes commands on AWS, you apss it a command and it implements a task_runner method , then you DONT need to know ANYTHING about the rest of the code, you can implement this bit as a completely isolated piece (this is the outsourcing part, now you can have a 100 people designign 100 different p[ieces, they don't need to know anything about the code, just the interfaces).
class Cat:
def meow(self):
print('meow')
def feed(cat):
cat.moew() # he thanks the owner
tom = Cat('Tom')
feed(tom)
C Sharp has the static type system. The compiler needs to know which methods the class has. That's why we must set type for every variable:
def feed(cat: Cat):
cat.moew() # he thanks the owner
But what if we have to write code and don't know what exactly type the variable must have?
def feed(it):
it.thank_owner()
Moreover we have to suppose our function will be used for various classes. Don't forget we must let the compiler know type of each variable! What to do? The solution:
class Pet: # an interface
def thank_owner(self):
raise NotImplementedError()
def feed(it: Pet):
it.thank_owner()
But what to do with Cat? The solution:
class Cat(Pet): # inherits the interface Pet
def thank_owner(self):
print('meow') # or self.meow() if we want to avoid big changes and follow DRY rule at the same time
tom = Cat('Tom')
feed(tom)
By the way now we can add new pets easy. We don't have to rewrite our code.
class Dog(Pet):
def thank_owner(self):
print('woof')
beethoven = Dog('Beethoven')
feed(beethoven) # yes, I use the same function. I haven't changed it at all!
Pay attention we created this class later than feed() and Pet. It's important we didn't think about Dog when writing code before. We were not curious about this. However we didn't have problems when we needed to extend the code.
Simple question. What would be the most pythonic way to make a class unable to be instantiated.
I know this could be done by overriding new __new__ and raising an exception there. Is there a better way?
I am kinda looking in the abstract class direction. However, I will NOT use this class as a base class to any other classes. And will NOT have any abstract methods defined in the class.
Without those, the abstract class does not raise any exceptions upon instantiation.
I have looked at this answer. It is not what I am looking for.
Is it possible to make abstract classes in Python?
Edit:
I know this might not be the best approach, but it is how I solved something I needed. I think it is a simple question, that can have a yes + explanation or no answer. Answers/comments that basically amount to, you should not be asking this question make very little sense.
what you're after is being able to just call something like, math.sin(x) right?
you make it a static method. and you just simply don't make any instances.
#staticmethod
def awesome_method(x): return x
if you're thinking why can't you actually do a = math()
because math, isn't a class. it's a separate script with all those functions in it.
so you may want to make a separate script with all your static things in it. ;)
if you want everything in the same script, then it's just local variables. and if you're like me, you'd rather them be organised properly with classes, looks like you'd probably be best just making a normal class, and creating just one instance of it
I recently went to an interview and did some little programming test where they had a simple two class script that would calculate the area, side length, etc.. Of a shape it looked something like this:
class Shape(object):
def __init__(self, side1, side2, side3, side4):
self.side1 = side1
...
#abstractmethod
def calc_area(self):
pass
class Triangle(Shape):
def calc_area(self):
... etc..
One of the questions they asked me was, if we ran help(Shape(3, 5, 5, 6)) what would happen assuming all objects have been initialized? my answer was, nothing because there's no docstring or __doc__. It appears that I was marked down on this answer and I can't seem to understand why? Was I incorrect in thinking that nothing would happen when running help()?
There are a couple of things in your description of the code that could be what they were expecting you to mention. It's not completely obvious to me which of these is an error of your memory of the code, and which is the real issue, but they are both things to think about:
The Shape class you show has an #abstractmethod in it. If it had a properly defined metaclass (something derived from abc.ABCMeta), you wouldn't be able to create any instances from it. Only concrete subclasses that override each of the abstract methods could be instantiated. So they may have expected you to say "you can't call help() on Shape(...) because the latter causes a TypeError.
Calling help on an instance will give you a description of each of the class's methods, even if it doesn't have a docstring. If a docstring exists, it will be displayed first, but the documentation for the methods (and descriptors, etc.) will always follow.
If you look at the source of pydoc.Helper class (especially its help() method), which is essentially what you get when you call help(), you'll see that it will still get the basic structure of your object using the inspect module and a couple of other tricks.
The goal being, of course, to provide at least object/function signature to other developers if the original code writers didn't bother with writing the docs. Personally, I don't see the reason of help() existing in the global namespace anyway, but I understand why they've placed it both from a historical and philosophical perspective.
That being said, whoever interviewed you was, IMO, a jerk - this doesn't really have to do much with programming but with nitpicking which is, may I say, quite un-Pythonic. That is, assuming that they weren't trying to get you on the #abstractmethod descriptor, of course, which might be a valid question.
I am new to OOP and am writing a small tool in Python that checks Bitcoin prices using a JSON load from the web Bitcoin() class, it monitors the prices Monitor(), notifies the user when thresholds are met Notify() and uses a console-interface Interface() for now to do so.
I have created a Bitcoin() class that can read the prices and volumes from the JSON load. The __init__ definition connects to the web using socket. Since every instance of this class would result in a new socket, I would only need/want one instance of this class running.
Is a class still the best way to approach this?
What is the best way to get other classes and instances to interact with my Bitcoin() instance?
Should I global a Bitcoin() instance? Pass the instance as an argument to every class that needs it?
The first thing which concerns me is the SRP violation, your Bitcoin class probably shouldn't be responsible for:
opening socket,
parsing results,
rendering output.
I don't know the details but from my point of view you should split that functionality to smaller classes/functions (in case of using only modules), and one of them will be responsible for retrieving data from web. Please also keep in mind that global state is evil (singletons in some contexts could be described as global state).
Another thing which is a smell from my point of view is opening a socket inside the constructor. This isn't testable, of course you could mock/stub socket, but from my point of view it's better when class requires all it's dependencies as a constructor parameter. By doing it that way you could also notice some classes with to wide responsibility (if your constructor requires more that 3,4 parameters it definitely could be simplified).
http://www.youtube.com/watch?v=o9pEzgHorH0
I'm not sure how relevant this video is for your project (no code to actually read). But maybe you'll pick up the answer to your question. At least you'll learn something new and that's what were here for.
If I were you my code would be something like:
( a class for every set of jobs, which is not what you are doing )
class Interface:
''' Handle UI '''
...
class Connect:
''' Handle web interface '''
...
class Bitcoin:
''' Handle the calculations '''
...
class Notify:
''' Notifier '''
...
In short, split your classes into smaller simpler classes.
Now for your question:
Yes, because you have a "complex-ish" problem at hand and you're using Python, so it's definitely easier to create a OOP version than a non-OOP one. So, unless you have a good reason not to, Stick to OOP.
In your case, it might as well be passing the instance as an argument.
This is a good idea. This eliminates the problems caused by scopes if you don't have a very good understanding of them.
But remember you pass the reference, not the value, so manipulating the instance, can and will affect other classes the instance is passed to.
Note: Opening a socket in the constructor of the class is not a good idea. It might be better if you have it in a method.
The answer is maybe. Depends upon you whole architecture,
You should look at the singleton pattern, because you description yells Singleton all over.
http://de.wikipedia.org/wiki/Singleton_%28Entwurfsmuster%29
If you don't find any good reason against creating a class in your given architecture, then just go for it.
OOP is a tool, not a goal, you can make a decision whether to use it or not. If you use a Python module, you can achieve encapsulation without ever writing "class".
Sure, you can use python classes for this purpose. You can use module-level instances as well(no global keyword or explicit passing as arguments needed). It is a matter of taste IMHO.
Basically you're asking about Singleton pattern python-specific implementation, it has been answered here:
Python and the Singleton Pattern
Description of pattern itself can be found here: http://en.wikipedia.org/wiki/Singleton_pattern
Let's say we have the following classes:
class Duck(object):
pass
class OldFashionedDuck(Organism, Duck):
def look(self):
self.display_biological_appearance()
def walk(self):
self.keep_balance_on_two_feet()
def quack(self):
self.make_noise_with_lungs("Quack!")
class ArtificialDuck(Robot, Duck):
def look(self):
self.display_imitation_biological_appearance()
def walk(self):
self.engage_leg_clockwork()
def quack(self):
self.play_sound("quack.au")
In this example, OldFashionedDuck and ArtificialDuck have no common implementation, but by construction they will both return True for isinstance(..., Duck).
This is not perfect, but it is something that I thought might help respect both duck typing, and (via empty mixin inheritance) allow isinstance(). In essence it offers a contract to meet an interface, so it's not really calling isinstance() based on the class that does all the work, but based on an interface that anyone can opt-in to.
I've seen articles based on "isinstance() considered harmful," because it breaks duck typing. However, I at least as a programmer would like to know, if not necessarily where an object gets a function from, but whether it implements an interface.
Is this approach useful, and if so can it be improved upon?
I've seen articles based on "isinstance() considered harmful," because it breaks duck typing. However, I at least as a programmer would like to know, if not necessarily where an object gets a function from, but whether it implements an interface.
I think you're missing the point.
When we talk about "duck typing", what we really mean is not formalizing our interfaces. What you're trying to do, therefore, boils down to attempting to answer the question "how can I formalize my interface while still not formalizing my interface?".
We expect an object that was given to us to implement an interface - one that we described, not by making a base class, but by writing a bunch of documentation and describing behaviour (and if we're feeling especially frisky, setting up some kind of test suite) - because we said that this is what we expect (again in our documentation). We verify that the object implements the interface by attempting to use it as though it does, and treating any resulting errors as the caller's responsibility. Calling code that gives us the wrong object is naughty, and that's where the bug needs to be fixed. (Again, tests help us track these things down.)
In short, testing isinstance(this_fuzzball_that_was_handed_to_me, Duck) doesn't really help matters:
It could pass the isinstance check, but implement the methods in a way that violates our expectations (or, say, return NotImplemented). Only real testing will do here.
It could pass the check, but actually completely fail to implement one or more of the methods; after all, the base Duck doesn't contain any implementations, and Python has no reason to check for them in a derived class.
Perhaps more importantly, it could fail the check, even though it's a perfectly usable-as-a-duck fuzzball. Maybe it's some unrelated object that had quack, walk and look functions directly, manually attached to it as attributes (as opposed to them being attributes of its class, which become methods when looked up).
Okay, so, "don't do that", you say. But now you're making more work for everyone; if clients don't always opt in, then it's useless and dangerous for the duck-using code to make the check. And meanwhile, what are you gaining?
This is related to the EAFP principle: don't try to figure out whether something is a Duck by looking at it; figure out if it's a Duck by treating it as a Duck and dealing with the gory mess if it isn't.
But if you don't care about the duck typing philosophy, and absolutely must force some semblance of rigor onto things, you might be interested in the standard library abc module.
Even though I don't want to overestimate this term, but: Your approach is not pythonic. Do duck-typing, or don't do it.
If you want to be sure that your implementation of a "interface" implements everything it should: test it!
For smaller projects, it's easy to remember what you need. And you can simply try it.
I agree that for larger projects, or even cooperation in teams, it's better to make sure that your type has everything it needs. In such a scenario, you definitely should use unit-tests to make sure your type is complete. Even without duck-typing, you need tests, so probably you won't need any extra-tests.
Guido van Rossum has talked about some interesting thoughts about duck-typing in this talk. It's so inspiring, and definitely worth watching.