-1

What happens in these two scenarios?

# Scenario 1
type(3) 
# <class 'int'>

type = "A random value"

# This will throw an error
type(3)
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable

Did we loose reference to type for the rest of the application?

# Scenario 2

class Foo:
   type = 3

bar = Foo()
bar.type
# 3
type(bar.type)
# <class 'int'>

What does that mean when using type as a django model field?

class FooBar(models.Model):
    baz = models.IntegerField(...)
    type = models.CharField(...)

And why does python allow assigning a value to type?

kokoi
  • 35
  • 1
  • 6
  • 2
    If you set `type` to a string, then it's not a function any more. – khelwood Jun 02 '21 at 08:18
  • 1
    Does this answer your question? [Why can you assign values to built-in functions in Python?](https://stackoverflow.com/questions/31865363/why-can-you-assign-values-to-built-in-functions-in-python) – adamkwm Jun 02 '21 at 08:21
  • @adamkwm Thank you that was quite informative, but what about assigning `type` within the class block? Will it have any implications within the rest of the class? – kokoi Jun 02 '21 at 08:26
  • `Foo.type` is a different variable from the global `type`. – khelwood Jun 02 '21 at 08:29
  • It still masked the built-in `type` within the same scope in class so it's better not to use built-in function name as variable to avoid confusion. – adamkwm Jun 02 '21 at 08:47
  • As it is obvious that one might hardly find oneself in the situation to *have* to use `type` as a variable name, this question was an attempt to try to understand the implications of using the name `type` as a class property, after having come across django models that declared `type` as a model field and worked fine. The linked question does not answer that @khelwood – kokoi Jun 02 '21 at 18:25
  • 1
    Then perhaps your question should have focused on the one aspect you want an answer to instead of asking four questions. – khelwood Jun 02 '21 at 18:31

1 Answers1

3

type is just a built-in function, you can override it like any other function

str = 5
print = "hello"

And why does python allow assigning a value to type?

Python in general almost never not allow you to do something, just like accessing private variables in classes, one of the principles of the language is trusting the dev to do whatever he needs

Ron Serruya
  • 3,988
  • 1
  • 16
  • 26